调用每个包含特定macros的button

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

这是我如何描绘它:

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 

我没有得到的是
我)如何检查button是否有一个特定的macros分配给它,和
ii)从所选button调用macros

既然你需要你的macros来知道哪个button叫它,你需要重新编码由button调用的macros以获得一个可选的参数。 调用macros时button不需要传递任何东西,所以它们不会改变,但是这个循环代码在调用macros时需要传递button。

例如,下面是一个button调用的示例macros,该macros被编码为可选参数:

 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 

然后这里是一个macros来循环,并为每个使用它的button调用该macros:

 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 

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

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

 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 

如果你的macros名称是固定的,这将做到:

 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 

如果它经常变化,你可以把它作为parameter passing:

 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 

这将做的伎俩 – 不知道如果没有macros附加到button,但会发生什么。

 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