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
4

1 回答 1

3

这从另一端解决了问题,根据是否填写了先前的组合框来启用或禁用组合框。在第三个组合框的情况下,级联事件是您的朋友,因为清除第一个组合框会触发第二个组合框的更改,这清除了第三个。将此代码添加到您的用户表单:

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
于 2012-10-27T14:50:44.400 回答