【问题标题】:VBA pass a control reference in a dynamic menuVBA 在动态菜单中传递控件引用
【发布时间】:2016-03-12 23:38:35
【问题描述】:

我在下面添加了一个右键单击单元格菜单,但想将子菜单的 .Caption 属性传递给处理程序; .OnAction someMacro(control .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

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

【问题讨论】:

    标签: vba excel


    【解决方案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 属性,但我自己从来没有这样做过.

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 2014-02-24
        • 1970-01-01
        • 1970-01-01
        • 2010-09-23
        • 2014-12-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-09
        • 2011-06-28
        相关资源
        最近更新 更多