如何从 Excel 2007 中的 VBA 访问复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6932084/
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-08 11:43:09  来源:igfitidea点击:

How to access Checkbox from VBA in Excel 2007

excelvbaexcel-2007

提问by Russell Steen

When adding a checkbox, how do you access the value from VBA?

添加复选框时,如何从 VBA 访问值?

  • In Excel 2007, on the Developer Ribbon
  • Insert, Form Controls, Checkbox
  • Renamed Checkbox to chkMyCheck
  • Added Macro to checkbox, I now have Module1 with chkMyCheck_Clicked
  • 在 Excel 2007 中,在开发人员功能区上
  • 插入、表单控件、复选框
  • 将复选框重命名为 chkMyCheck
  • 将宏添加到复选框,我现在有带有 chkMyCheck_Clicked 的 Module1

All of the following fail

以下所有失败

Sheets("Sheet1").chkMyCheck.Checked  
Sheets("Sheet1").chkMyCheck.Value  
Sheets("Sheet1").Shapes("chkMyCheck").Checked  
Sheets("Sheet1").Shapes("chkMyCheck").Value  
Sheet1.chkMyCheck.Checked  
Sheet1.chkMyCheck.Value  

Sheet1.Shapes("chkMyCheck") appears to find the object, but does not expose any properties that look likely for returning the checked state.

Sheet1.Shapes("chkMyCheck") 似乎找到了对象,但没有公开任何看起来可能返回选中状态的属性。

回答by Russell Steen

Figured it out

弄清楚了

If Sheet1.Shapes("chkMyCheck").ControlFormat.Value = xlOn Then
.....

回答by Tim Williams

One way:

单程:

Dim oCheck As Object
Set oCheck = Sheet1.CheckBoxes("chkMyCheck")
MsgBox (oCheck.Value = xlOn)

Edit: here's another method - maybe this one will work for you...

编辑:这是另一种方法 - 也许这个方法对你有用......

Sub Tester2()
    Dim sh As Shape
    For Each sh In Sheet1.Shapes
        If sh.Type = msoFormControl Then
            If sh.FormControlType = xlCheckBox Then
                 Debug.Print sh.Name & "=" & sh.ControlFormat.Value
            End If
        End If
    Next sh
End Sub

回答by Brian Burns

For completeness, if you're using an ActiveX checkbox instead of a regular checkbox, the syntax is

为完整起见,如果您使用的是 ActiveX 复选框而不是常规复选框,则语法为

If Sheet1.Shapes("chkMyCheck").OLEFormat.Object.Object.Value Then 
...

found using the Locals window and a variable set to the shape -

使用 Locals 窗口和设置为形状的变量找到 -

Dim shp as Shape
Set shp = Sheet1.Shapes("chkMyCheck")
Stop