在VBA事件处理程序中获取对“表单”checkbox的引用
我在Excel 2010中有一些表单checkbox。点击时需要执行一些常用的代码。 要做到这一点,我想通过checkbox的引用,但到目前为止,我只能够得到它作为一个形状input。
为了抢占这个问题,是的,他们需要成为Form Checkboxes而不是ActiveX Checkboxes。
我是一个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
这与Siddharth的类似,但添加了Shape
的ControlFormat
属性。 在这种情况下, ControlFormat
会为您提供CheckBox
的Intellisense 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
在这种情况下,所有checkbox都没有不同的点击事件。 只有一个。 并使用Application.Caller
来获取调用它的cckckbox的名称。 将其作为String
传递给相关的子部分,然后使用它。
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
您也可以将两者合并为一个,并将其与所有checkbox链接起来。
Sub DoSomething() Dim shp As shape Set shp = ActiveSheet.Shapes(Application.Caller) With shp '~~> Do something End With End Sub