调用包含某个宏的每个按钮

时间:2015-10-06 13:36:47

标签: excel vba excel-vba button

我正在尝试为每个循环检查活动工作表中的每个按钮以查看该按钮是否包含某个宏。如果为按钮分配了正确的宏,那么我希望按钮调用sub,然后转到下一个按钮。

这是我拍照的方式:

Sub ExecuteAllButtonsContainingX()

Dim Btn As Button   
Dim Btn_count As Integer

Btn_count = 1

For Each Btn In Application.Workbooks.ActiveSheet.Buttons
    Btn(Btn_count).Select  

    If ***[The selected button contains Macro X]*** Then
        ***[Call the macro that is assigned to the selected button as if the button was clicked on]***
    Else
    End If    

    Btn_count = Btn_count + 1

Next Btn

End Sub

我没有得到的是 i)如何检查按钮是否分配了某个宏,以及
ii)从所选按钮调用宏

4 个答案:

答案 0 :(得分:2)

这是你如何做到的(代码注释):

Sub ExecuteAllButtonsContainingX()
    Dim Btn As Button
    'Counter is redundant if you use [For Each] loop.
    'Dim Btn_count As Integer
    '-------------------------------------------------

    'Btn_count = 1


    For Each Btn In ActiveSheet.Buttons

        'Btn(Btn_count).Select      '<--- This is redundant. You don't have to
                                    '     select button to check its properties.


        'If property [OnAction] of the current button is not empty
        'it means there is some macro assigned to this button.
        If Len(Btn.OnAction) Then

            'This action is called only if there is some macro
            'assigned to the current button.
            Call Application.Run(Btn.OnAction)

        End If

        'Btn_count = Btn_count + 1

    Next Btn

End Sub

答案 1 :(得分:1)

这样可以解决问题 - 不确定如果按钮没有附加宏,会发生什么。

Sub ExecuteAllButtonsContainingX()

    Dim Btn As Shape

    For Each Btn In Sheet1.Shapes
        If Btn.FormControlType = xlButtonControl Then
            Run Btn.OnAction
        End If
    Next Btn

End Sub

答案 2 :(得分:1)

如果您的宏名称已修复,则执行以下操作:

Sub ExecuteAllButtonsContainingX()
Dim Btn As Button

For Each Btn In ActiveSheet.Buttons

    If Btn.OnAction = "insertMacroNameHere" Then

        Run Btn.OnAction

    End If

Next Btn

End Sub

如果它经常更改,您可以将其作为参数传递:

Sub ExecuteAllButtonsContainingX(macroName As String)
Dim Btn As Button

For Each Btn In ActiveSheet.Buttons

    If Btn.OnAction = macroName Then

        Run Btn.OnAction

    End If

Next Btn

End Sub

答案 3 :(得分:0)

由于您需要宏知道哪个按钮调用它,因此您需要重新编码按钮调用的宏以获取可选参数。调用宏时,按钮不需要传递任何内容,因此它们不会发生变化,但是这个循环代码在调用宏时需要传递按钮。

例如,这里是按钮调用的示例宏,编码为可选参数:

Sub foomsg(Optional vButton As Variant)
    Dim btn                   As Button
    If IsMissing(vButton) Then
        Set btn = ActiveSheet.Buttons(Application.Caller)
    Else
        Set btn = vButton
    End If
    MsgBox btn.Name
End Sub

然后这是一个宏来循环并为每个使用它的按钮调用该宏:

Sub foo()
    Dim btn                   As Button
    Dim sMacroName            As String
    Dim cf                    As ControlFormat

    sMacroName = "foomsg"
    For Each btn In ActiveSheet.Buttons
        If Right$(btn.OnAction, Len(sMacroName)) = sMacroName Then
            Run btn.OnAction, btn
        End If
    Next btn
End Sub

希望这是有道理的。如果没有,请问!