我想遍历窗体上的控件并读取值。但是,“值”和“已检查”属性不可用。我的问题是,当我循环浏览控件时,如何读取控件的值(在本例中为复选框)?
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
答案 0 :(得分:4)
循环控件并检查TypeName。
Dim c As Control
For Each c In Me.Controls
If TypeName(c) = "CheckBox" Then
MsgBox c.Value
End If
Next
答案 1 :(得分:2)
TypeName
会有效,但在一天结束时,它会进行字符串比较。
VBA中强类型类型检查的实际语法如下:
TypeOf [object] Is [Type]
所以:
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
现在,有点笨拙的是,MSForms库正在使OptionButton
和CheckBox
实现相同的接口(实际上并不是那么令人惊讶),因此对于这两种类型的上述条件都是True
控制;您可以使用其他类型检查过滤掉OptionButton
:
If TypeOf ctrl Is MSForms.CheckBox And Not TypeOf ctrl Is MSForms.OptionButton Then
可以说,使用TypeName
更简单,至少在这种情况下MSForms
令人讨厌。但是,当您开始需要在VBA中进行类型检查时, 了解TypeOf ... Is
。