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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 12:26:20  来源:igfitidea点击:

VBA - Loop through Controls on a form and read the value

vba

提问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

TypeNamewill 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 OptionButtonand CheckBoximplement the same interface (not all that surprising actually), so the above condition will be Truefor both types of controls; you can filter out the OptionButtonwith another type check:

现在,有点尴尬的是 MSForms 库正在制作OptionButtonCheckBox实现相同的接口(实际上并不那么令人惊讶),因此上述条件将True适用于两种类型的控件;您可以OptionButton使用另一种类型检查过滤掉:

If TypeOf ctrl Is MSForms.CheckBox And Not TypeOf ctrl Is MSForms.OptionButton Then

Arguably, using TypeNameis simpler, at least in this case where MSFormsis being annoying. But you haveto know about TypeOf ... Iswhen you start needing to do type checks in VBA.

可以说,使用TypeName更简单,至少在这种情况下MSForms令人讨厌。但是您必须知道TypeOf ... Is何时开始需要在 VBA 中进行类型检查。