检查多个文本框/combobox的input

我有一个用户窗体与多个combobox和文本框,我用来input数据到工作表。 我一直在寻找的是一个代码,将数据保存到工作表之前将检查所有这些框,所以如果一个是空的,它会popup一条消息,而不是保存数据。

我一直在使用一个函数来逐个检查每个函数,但是如果其他函数是空的,它仍然会将数据保存到表单中。

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

你可能想尝试如下所示

 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代码窗格中

创build一个checkbox控件对象的数组,然后遍历它依次检查每个对象。