VBA 使用循环引用文本框或标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6060142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Refer to TextBox or Label using a loop
提问by John M
I am trying to replace the following:
我正在尝试替换以下内容:
txt1.Text = ""
txt2.Text = ""
txt3.Text = ""
txt4.text = ""
...continues for quite awhile
With:
和:
Dim cCont As Control
For Each cCont In Me.Controls
If TypeName(cCont) = "TextBox" Then
'reset textbox value
???
End If
Next cCont
How do I refer to the textbox using the generic 'Control'?
如何使用通用“控件”引用文本框?
回答by GSerg
You already have your control in cCont.
您已经可以控制 cCont。
Dim cCont As Control
For Each cCont In Me.Controls
If TypeOf cCont Is MSForms.TextBox Then
cCont.Text = "hi"
MsgBox cCont.Name
End If
Next
If you're confused by the fact you don't get the Text
property from IntelliSense, just cast the Control
to a more derived type:
如果您对没有Text
从 IntelliSense获取属性这一事实感到困惑,只需将Control
转换为更派生的类型:
Dim cCont As Control
For Each cCont In Me.Controls
If TypeOf cCont Is MSForms.TextBox Then
Dim cText As MSForms.TextBox
Set cText = cCont
cText.Text = "hi"
MsgBox cText.Name
End If
Next
This will use early binding instead of late binding, and you'll get your code suggestions.
这将使用早期绑定而不是后期绑定,您将获得代码建议。