【问题标题】:VBA macro : find button by location and 'click' them [closed]VBA宏:按位置查找按钮并“单击”它们[关闭]
【发布时间】:2018-07-25 14:03:40
【问题描述】:

我正在尝试制作一个宏。从行索引和列索引检测该单元格上是否有一个或多个按钮并执行附加到该按钮的代码。

我没有找到 'find_button_by_location' 方法和 'button.execute_as_clicked'

我想知道是否有人可以帮助我提出一些建议。

谢谢

【问题讨论】:

  • 按钮是一个控件。您不会按单元格搜索它们的位置,更传统的是,如果您正在寻找特定按钮,您将循环浏览工作表上的对象并查找某些名称。按钮在 VBA 中没有按下或没有“状态”,当您单击一个它会调用一个事件,该事件是
  • 您不想随机执行按钮代码。您想确定正在执行的代码以及目标按钮。按住变量中的按钮并使用它们。
  • @JarBeans:欢迎来到 Stack Overflow:请 take the tour 并阅读 How to ask a good question,然后编辑您的问题以包含代码、预期行为以及问题所在......然后我们可以尝试帮助
  • 我拒绝/投票关闭,因为您没有包含 Minimal, Complete, Verifiable Example ,看起来像 no attempt was made

标签: vba excel button


【解决方案1】:

这样的事情可能对你有用:

Sub ClickButton(ByVal arg_rCells As Range)

    Dim ws As Worksheet
    Dim oOLE As OLEObject
    Dim shp As Shape
    Dim hButtons As Object

    Set ws = arg_rCells.Parent
    Set hButtons = CreateObject("Scripting.Dictionary")

    'ActiveX buttons
    For Each oOLE In ws.OLEObjects
        hButtons.Add oOLE.Name, oOLE.Name
        If Not Intersect(arg_rCells, ws.Range(oOLE.TopLeftCell, oOLE.BottomRightCell)) Is Nothing Then
            Run "'" & ws.Parent.Name & "'!" & ws.CodeName & "." & oOLE.Name & "_Click"
        End If
    Next oOLE

    'Form Control buttons
    For Each shp In ActiveSheet.Shapes
        If Not hButtons.exists(shp.Name) Then
            hButtons.Add shp.Name, shp.Name
            If Not Intersect(arg_rCells, ws.Range(shp.TopLeftCell, shp.BottomRightCell)) Is Nothing Then
                Run shp.OnAction
            End If
        End If
    Next shp

End Sub

这是一个如何调用它的示例(如果单元格 C3 中存在一个按钮,这将单击一个按钮):

Sub tgr()

    ClickButton ActiveSheet.Range("C3")

End Sub

【讨论】:

  • 谢谢@tigeravatar,它真的对我有帮助,现在我对它的工作原理有了更好的了解。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
相关资源
最近更新 更多