Loop to check if TextBoxes are not empty

2019-07-23 16:37发布

I try to For loop through all controls on a form to check if a TextBox is empty. Then puts focus on the first empty TextBox.

My Excel VBA Form has 34 TextBox. For now it has a nested If function that checks if all TextBoxes are not empty. If there are any empty .SetFocus on the 1st empty TextBox.

Sub ValidateForm()
  If TextBox1.Text = Empty Then
      TextBox1.SetFocus
  Else    
       If TextBox2.Text = Empty Then .........

Imagine this with 34 nesting?
So I tried the For Each loop solution. But it's not working! Any idea?

Sub ValidarForm5()
    For Each ctrl In UserForm1.Controls
        If TypeName(ctrl) = "TextBox" Then
            If ctrl.Text = Empty Then
                ctrl.SetFocus
            End If
        End If
    Next ctrl
End Sub

2条回答
We Are One
2楼-- · 2019-07-23 16:59

Your ValidarForm5 code works. I've tested it on a Userform without throwing any errors. @Peh has provided an solution in his comment but I thought I'd expand by explaining what your code is doing now.

You are looping through all 34 textboxes, one at a time. So you're testing TextBox1 to see if it is empty. If it is, then you SetFocus to that Textbox1. Then you move to TextBox2 and test that. If it's empty, then you SetFocus to that Textbox2.. and on.. and on..

So this means that if the last TextBox (Textbox34) is empty, then that will be the last one that has focus set to it. If that isn't empty, then it'll be the one before, etc.. etc..

What you're after though, is the first Textbox that is empty. As @Peh mentions, you just need to drop out of your loop once the first one is set. This is easily done with Exit For like so:

Sub ValidarForm5()
    For Each ctrl In UserForm1.Controls
        If TypeName(ctrl) = "TextBox" Then
            If ctrl.Text = Empty Then
                ctrl.SetFocus
                Exit For
            End If
        End If
    Next ctrl
End Sub
查看更多
Root(大扎)
3楼-- · 2019-07-23 17:01

If your are using your code within the UserForm itself use Me instead of UserForm1 and declare your variables. If found an empty TextBox you have to Exit the For Loop, otherwise you won't remain in it.

Code in UserForm

Option Explicit    ' declaration head of your userform code module

Sub ValidateForm()
Dim ctrl As Object
For Each ctrl In Me.Controls
    If TypeName(ctrl) = "TextBox" Then
        If ctrl.Text = Empty Then
            ctrl.SetFocus
            Exit For    ' escape to remain in found textbox
        End If
    End If
Next ctrl
End Sub
查看更多
登录 后发表回答