检查多个文本框/组合框以进行输入

时间:2016-04-24 16:25:46

标签: excel vba excel-vba

我有一个userform,其中包含多个组合框和文本框,用于将数据输入到工作表中。我一直在寻找的是一个代码,它会在将数据保存到工作表之前检查所有这些框,因此如果一个为空,它将弹出一条消息而不保存数据。

我一直在使用一个单独检查每个功能的功能,但如果其他人是空白的话,它仍然会将数据保存到工作表中。

Public Function CheckEmpty(text_box As Object) As Boolean
CheckEmpty = (Len(Trim(text_box.Value)) > 0)
End Function

2 个答案:

答案 0 :(得分:1)

你可能想尝试类似下面的内容

Private Sub CommandButton1_Click() '<== change "CommandButton1" with the actual 'closing' button name
Dim ctrl As Control
Dim msg As String

With Me
    For Each ctrl In .Controls

        Select Case TypeName(ctrl)

            Case "ComboBox"
                If ctrl.ListIndex = -1 Then msg = msg & vbCrLf & "ComboBox '" & ctrl.name & "' with no value selected"
            Case "TextBox"
                If ctrl.text = "" Then msg = msg & vbCrLf & "TextBox '" & ctrl.name & "' with no value selected"
            Case Else

        End Select

    Next ctrl

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

End Sub

放在UserForm代码窗格

答案 1 :(得分:0)

创建一个复选框控件对象的数组,然后迭代它依次检查每个对象。

相关问题