VBA在dynamic菜单中传递控件引用

我在下面添加一个右键单元格菜单,但想要将子菜单的.Caption属性传递给处理程序; .OnAction someMacro(control.Caption),但它似乎只允许引用macros的string; .AnAction“someMacro”

' Add a custom submenu with three buttons. Set mySubMenu = ContextMenu.Controls.Add(Type:=msoControlPopup, BEFORE:=1) With mySubMenu .Caption = "Some Materials" .Tag = "Some_Cell_Control_Tag" For Each Item In substrateRng With .Controls.Add(Type:=msoControlButton) ' using this onAction item causes recursive event to fire? '.OnAction = addSubstrate("kkkkk") .OnAction = "addSubstrate" '.FaceId = 95 .Caption = Item.Value End With Next Item End With 

所以我正在寻找如何将选定的菜单项的标题传递给一个通用的动作,否则,似乎我必须将每个菜单项的动作编码到一个独特的macros?

可以在OnAction属性中传递参数。 假设你的参数是一个String那么你可以把整个属性用单引号括起来,每个参数用双引号括起来。

在你的情况下, Sub可能看起来有点像这样:

 Public Sub addSubstrate(strValue as String) '...' End Sub 

而你的呼叫路线是:

 With .Controls.Add(Type:=msoControlButton) .Caption = Item.Value .OnAction = "'addSubstrate """ & .Caption & """'" End With 

我相信你也可以传递对象,所以你可以有一种Sender参数,并传递控件本身,以便你可以在处理例程中访问它的.Caption属性,但我从来没有这样做过。

 For Each Item In substrateRng With .Controls.Add(Type:=msoControlButton) ' using this onAction item causes recursive event to fire? '.OnAction = addSubstrate("kkkkk") .OnAction = "addSubstrate" '.FaceId = 95 .Caption = Item.Value .parameter = .caption 'here you add the parameter value as desired End With Next Item 

在你的addsubstrate函数中,添加一行来查询参数:

 dim paramInput as String paramInput = Application.CommandBars.actionControl.parameter ' Or you could just use Application.CommandBars.actionControl.Caption