VBA - 循环遍历表单上的控件并读取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43330669/
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 - Loop through Controls on a form and read the value
提问by SQLiz
I would like to loop through controls on a form and read the value. However the Value and Checked properties are not available. My question is, how can I read the value of a control (in this case a checkbox) when I loop through them?
我想遍历表单上的控件并读取值。但是 Value 和 Checked 属性不可用。我的问题是,当我遍历控件时,如何读取控件的值(在本例中为复选框)?
Dim Ctrl as Control
For Each Ctrl In frmMaintenance.Controls
If Left(Ctrl.Name, 7) = "chkType" And **Ctrl.Value = True** Then
End if
Next Ctrl
回答by Sorceri
loop through the controls and check the TypeName.
遍历控件并检查 TypeName。
Dim c As Control
For Each c In Me.Controls
If TypeName(c) = "CheckBox" Then
MsgBox c.Value
End If
Next
回答by Mathieu Guindon
TypeName
will work, but at the end of the day it's a string comparison.
TypeName
会起作用,但归根结底是字符串比较。
The actual syntax for strongly-typed type checks in VBA goes like this:
VBA 中强类型类型检查的实际语法如下所示:
TypeOf [object] Is [Type]
So:
所以:
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeOf ctrl Is MSForms.CheckBox Then
Debug.Print TypeName(ctrl), ctrl.Name, ctrl.Value
End If
Next
Now, somewhat awkwardly the MSForms library is making OptionButton
and CheckBox
implement the same interface (not all that surprising actually), so the above condition will be True
for both types of controls; you can filter out the OptionButton
with another type check:
现在,有点尴尬的是 MSForms 库正在制作OptionButton
和CheckBox
实现相同的接口(实际上并不那么令人惊讶),因此上述条件将True
适用于两种类型的控件;您可以OptionButton
使用另一种类型检查过滤掉:
If TypeOf ctrl Is MSForms.CheckBox And Not TypeOf ctrl Is MSForms.OptionButton Then
Arguably, using TypeName
is simpler, at least in this case where MSForms
is being annoying. But you haveto know about TypeOf ... Is
when you start needing to do type checks in VBA.
可以说,使用TypeName
更简单,至少在这种情况下MSForms
令人讨厌。但是您必须知道TypeOf ... Is
何时开始需要在 VBA 中进行类型检查。