2012-10-27 47 views
0

我有一個問題一次驗證三個下拉列表。這裏是測試用例:防止驗證錯誤發生的雙重實例

cbo_fac1 - user must select this as a pre-requisite for cbo_fac1 and cbo_fac2 
cbo_fac2 - user must select cbo_fac1 as a pre-requisite 
cbo_fac3 - user must select cbo_fac1 and cbo_fac2 as a pre-requisite 

這是我目前使用的代碼。不幸的是,在某些情況下,即如果用戶首先嚐試選擇cbo_fac3,它似乎循環了幾個錯誤。有沒有什麼辦法可以合併這些函數,並讓它在每種情況下只顯示一次錯誤?

Private Sub cbo_fac2_Enter() 

    If Len(cbo_fac1.Value) = 0 Then 
     MsgBox ("Please select a first preference before selecting a second preference") 
     cbo_fac1.SetFocus 
     Exit Sub 
    End If 

End Sub 

Private Sub cbo_fac3_Enter() 

    If Len(cbo_fac2.Value) = 0 & Len(cbo_fac3.Value) = 0 Then 
     MsgBox ("Please select a first preference before selecting a second/third preference") 
     cbo_fac1.SetFocus 
     Exit Sub 
    End If 

    If Len(cbo_fac2.Value) = 0 Then 
     MsgBox ("Please select a second preference before selecting a third preference") 
     cbo_fac2.SetFocus 
     Exit Sub 
    End If 

End Sub 

回答

3

這從另一端靠近的問題,從而實現或者基於那些以前是否被填入禁用組合框,在這裏級聯事件是你在第3組合框的情況下,朋友,清除1號在第二個觸發一個變化,清除第三個。此代碼添加到您的用戶窗體:

Private Sub cbo_fac1_Change() 
With cbo_fac2 
.Enabled = Len(cbo_fac1.Value) > 0 
If Not .Enabled Then 
    .ListIndex = -1 
End If 
End With 
End Sub 

Private Sub cbo_fac2_Change() 
With cbo_fac3 
    .Enabled = Len(cbo_fac2.Value) > 0 
    If Not .Enabled Then 
     .ListIndex = -1 
    End If 
End With 
End Sub 

剛一說明,如果你最終有一個更長的一系列的這些,你要尋找到一個WITHEVENTS控制類。

此外,儘可能地嘗試避免用戶輸入控件時出現錯誤消息框。試着用視覺提示來引導他們 - 在這種情況下禁用空的控制 - 或者等到他們點擊OK後告訴他們他們需要改變。

如果任何人想嘗試了這一點,創建形式與3個組合框,然後這個初始化代碼添加到您的形式:

Private Sub UserForm_Initialize() 
Dim i As Long 

With Me 
    With .cbo_fac1 
     For i = 1 To 10 
      .AddItem .Name & i 
     Next i 
    End With 
    With .cbo_fac2 
     For i = 1 To 10 
      .AddItem .Name & i 
     Next i 
     .Enabled = False 
    End With 
    With .cbo_fac3 
     For i = 1 To 10 
      .AddItem .Name & i 
     Next i 
     .Enabled = False 
    End With 
End With 
End Sub