如何跳过一个检查复选框值的文本框?

时间:2017-08-28 20:24:34

标签: excel-vba vba excel

我有一个包含多个文本框,组合框,复选框等的用户表单。 我编写了一个代码来检查控件的值是否为null - textbox&组合框 - 比结束子

Dim ctrl As Control
Dim msg1 As String
Dim msg2 As String
Dim msg As String

With Me
For Each ctrl In NewJoinerEntry.Controls

    Select Case TypeName(ctrl)
        Case "TextBox"
            If ctrl.Text = "" Then msg1 = "TextBox"
        Case "ComboBox"
            If ctrl.ListIndex = -1 Then msg2 = "ComboBox"
        Case Else
    End Select

Next ctrl
msg = "Please enter complete details in " & msg1 & " & " & msg2 & "."

If msg = "" Then
    .Hide ' hide the userform only if no empty textboxes and/or comboboxes
Else
    MsgBox msg
    Exit Sub
End If
End With

上面的代码工作正常但是 - userform中有一个文本框,仅当复选框值为yes时才会激活。

上面的代码也要求为该文本框输入值。想要从正在检查空值的循环中消除该文本框。

1 个答案:

答案 0 :(得分:0)

忽略不是.Enabled的控件:

For Each ctrl In NewJoinerEntry.Controls

    If ctrl.Enabled Then
        Select Case TypeName(ctrl)
            Case "TextBox"
                If ctrl.Text = "" Then msg1 = "TextBox"
            Case "ComboBox"
                If ctrl.ListIndex = -1 Then msg2 = "ComboBox"
            Case Else
        End Select
    End If
Next ctrl

通过在If ctrl.Enabled循环中添加For Each逻辑,我们只是指示代码绕过/忽略任何不是Enabled=True的控件。根据需要进行微调或修改。

你可能也应该修改如下:

msg =  msg1 & " & " & msg2 

If msg = "" Then
    .Hide ' hide the userform only if no empty textboxes and/or comboboxes
Else
    MsgBox "Please enter complete details in " & msg & "."
    Exit Sub
End If