Code to Loop Through the COntrols of Userform and

2019-09-07 04:06发布

I have a userform whose image is attached below. enter image description here

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条回答
看我几分像从前
2楼-- · 2019-09-07 04:53

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
查看更多
登录 后发表回答