Code to Loop Through the COntrols of Userform and Prompt if any field is empty

你离开我真会死。 提交于 2020-01-07 02:51:09

问题


I have a userform whose image is attached below.

What i need is when i press the submit button, it should promptv if there is any textbox left empty in the userform.

Here is my code:

Private Sub CommandButton1_Click()

Dim intTextBox As Integer
For intTextBox = 1 To 2

If Controls("TextBox" & intTextBox) = "" Then
MsgBox ("TextBox" & intTextBox & "blank. Please enter relevant data!")
Exit For
End If
Next intTextBox

End Sub

I am getting error at If Controls("TextBox" & intTextBox) = "" Then as could not find the specified object.

Kindly review and advise.


回答1:


In order to find which TextBox is left empty, you need to loop through all Controls in your user_Form. Then, for each Control you need to check if it's type TextBox >> if it is, then check if it's empty.

Code

Option Explicit

Private Sub CommandButton1_Click()

Dim ctrl As Control

' loop through all controls in User_Form
For Each ctrl In Me.Controls
    ' check if "TextBox"
    If TypeName(ctrl) = "TextBox" Then

        ' if current TextBox is empty
        If ctrl.Text = "" Then
            MsgBox ctrl.Name & "blank. Please enter relevant data!"
            Exit For
        End If

    End If

    ' check if "ComboBox"
    If TypeName(ctrl) = "ComboBox" Then

        ' if current ComboBox is empty
        If ctrl.Value = "" Then
            MsgBox ctrl.Name & "blank. Please enter relevant data!"
            Exit For
        End If

    End If
Next ctrl

End Sub


来源:https://stackoverflow.com/questions/40816057/code-to-loop-through-the-controls-of-userform-and-prompt-if-any-field-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!