VBA宏:按位置查找按钮,然后“单击”它们

时间:2018-07-25 14:03:41

标签: excel vba excel-vba button

我正在尝试删除宏。通过行索引和列索引来检测此单元格上是否有一个或多个按钮,并执行此按钮所附的代码。

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

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

谢谢

1 个答案:

答案 0 :(得分: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