循环检查TextBoxes是否为空 [英] Loop to check if TextBoxes are not empty
问题描述
我尝试For
循环遍历窗体上的所有控件,以检查TextBox是否为空.然后将焦点放在第一个空的TextBox上.
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.
我的Excel VBA表单具有34个文本框.目前,它具有嵌套的If
函数,该函数检查所有TextBoxes是否都不为空.如果第一个空TextBox上有任何.SetFocus
.
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 .........
想像一下它有34个嵌套吗?
因此,我尝试了For Each
循环解决方案.但这是行不通的!有什么主意吗?
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
推荐答案
如果您在UserForm本身中使用代码,请使用Me
而不是UserForm1
并声明您的变量.如果发现一个空的TextBox,则必须退出For
循环,否则您将不会停留在其中.
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.
用户窗体中的代码
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
这篇关于循环检查TextBoxes是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!