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
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 youSetFocus
to thatTextbox1
. Then you move toTextBox2
and test that. If it's empty, then youSetFocus
to thatTextbox2
.. 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 withExit For
like so:If your are using your code within the UserForm itself use
Me
instead ofUserForm1
and declare your variables. If found an empty TextBox you have to Exit theFor
Loop, otherwise you won't remain in it.Code in UserForm