在 VBA 事件处理程序中获取对 Forms 复选框的引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20613945/
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
Get reference to Forms checkbox in VBA event handler
提问by MgSam
I have some Forms Checkboxes in Excel 2010. I need to perform some common code when they are clicked. To do this, I'd like to pass a reference to the Checkbox, but so far I'm only able to get it typed as a shape.
我在 Excel 2010 中有一些表单复选框。单击它们时我需要执行一些通用代码。为此,我想传递对复选框的引用,但到目前为止,我只能将其输入为形状。
To preempt the question, yes, they need to be Form Checkboxes and not ActiveX Checkboxes.
为了抢占问题,是的,它们需要是表单复选框而不是 ActiveX 复选框。
I'm a novice with VBA, so any help is appreciated.
我是 VBA 的新手,因此感谢您的帮助。
Sub CheckBox1_Click()
'I really want this reference to be a Checkbox, not a Shape
Dim shape As Shape
Set shape = ActiveSheet.Shapes("Check Box 1")
DoSomething(shape)
End Sub
Sub DoSomething(MSForms.CheckBox)
'I need the reference to be a checkbox as I need to check
'whether it's checked or not here
End Sub
回答by Siddharth Rout
In such a scenario, don't have different click event for all checkboxes. Have just one. And use Application.Caller
to get the name of the ckeckbox which called it. Pass that as a String
to the relevant sub and then work with it.
在这种情况下,不要为所有复选框设置不同的点击事件。只有一个。并用于Application.Caller
获取调用它的 ckeckbox 的名称。将它作为 aString
传递给相关的子,然后使用它。
UNTESTED
未经测试
Sub CheckBoxMain_Click()
Dim sName As String
sName = Application.Caller
DoSomething (sName)
End Sub
Sub DoSomething(sCheck As String)
Dim shp As shape
Set shp = ActiveSheet.Shapes(sCheck)
With shp
'~~> Do something
End With
End Sub
You could also combine the two into one as well and link it with all checkboxes.
您也可以将两者合二为一,并将其与所有复选框链接。
Sub DoSomething()
Dim shp As shape
Set shp = ActiveSheet.Shapes(Application.Caller)
With shp
'~~> Do something
End With
End Sub
回答by Doug Glancy
This is similar to Siddharth's but adds the ControlFormat
property of the Shape
. ControlFormat
gets you the Intellisense for the CheckBox
, in this case Value
:
这类似于 Siddharth 的,但增加ControlFormat
了Shape
. ControlFormat
为您提供 的智能感知CheckBox
,在这种情况下Value
:
Sub CheckBox1_Click()
Dim chk As Shape
Set chk = ActiveSheet.Shapes(Application.Caller)
With chk.ControlFormat
If .Value = True Then
MsgBox "true"
Else
MsgBox "false"
End If
End With
End Sub