VBA在动态菜单中传递控件参考

时间:2016-03-12 23:38:35

标签: excel vba excel-vba

我在下面添加了一个右键单元格菜单,但是想将子菜单的.Caption属性传递给处理程序; .OnAction someMacro(控制.Caption)但它似乎只允许一个引用宏的字符串; .OnAction“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

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

2 个答案:

答案 0 :(得分:1)

可以在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属性,但我已经从来没有这样做过。

答案 1 :(得分:0)

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