【问题标题】:Get reference to Forms checkbox in VBA event handler在 VBA 事件处理程序中获取对表单复选框的引用
【发布时间】:2013-12-16 15:00:19
【问题描述】:

我在 Excel 2010 中有一些表单复选框。我需要在单击它们时执行一些通用代码。为此,我想传递对复选框的引用,但到目前为止,我只能将其键入为形状。

要抢占问题,是的,它们需要是表单复选框而不是 ActiveX 复选框。

我是 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

【问题讨论】:

  • 表单类别中工作表的复选框属于形状类型。你不能将它们cast为 CheckBox 类型

标签: vba excel office-2010


【解决方案1】:

在这种情况下,不要为所有复选框设置不同的点击事件。就一个。并使用Application.Caller 获取调用它的ckeckbox 的名称。将其作为 String 传递给相关的子,然后使用它。

未经测试

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

您也可以将两者合二为一,并将其​​与所有复选框链接。

Sub DoSomething()
    Dim shp As shape

    Set shp = ActiveSheet.Shapes(Application.Caller)

    With shp
        '~~> Do something
    End With
End Sub

【讨论】:

  • 我的理解是 Excel 不允许您为多个控件使用公共事件处理程序。这不是真的吗?相信我,我什么都不想要了。不过,这并不能解决我的问题。我需要将形状键入为具有 Value 属性的 Checkbox,在您的代码中它仍然键入为 Shape。
  • @MgSam:那是因为你说它是表单控件而不是 ActiveX 控件?对于表单控件,您可以使用一个子
  • 啊,谢谢。这很有帮助。你知道我如何检查它的 Value 属性以查看它是否被选中?
【解决方案2】:

这类似于 Siddharth 的,但添加了 ShapeControlFormat 属性。 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

【讨论】:

  • @SiddharthRout,我查看了链接。你的评论是什么意思?
  • 我已经对你的答案投了赞成票 :) 我在我的答案的 cmets 中发布了上面的评论。只是想让你知道它已经被覆盖了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2012-05-26
相关资源
最近更新 更多