Excel VBA CommandBar.OnAction with params is difficult / does not perform as expected

后端 未结 3 1003
误落风尘
误落风尘 2021-01-19 01:09

So, I have Googled about and it seems that while making custom Pop up menus, if one wants to pass parameters then this is possible but for me comes with 2 major pro

3条回答
  •  余生分开走
    2021-01-19 01:46

    Don't ask me why this works, but it does. Source for this info is Using procedures with arguments in non-obvious instances

    Sub AssignIt()
    Const strCBarName As String = "MyNewPopupMenu"
    Dim cbrCmdBar As CommandBar
    
        'Delete it first so multiple runs can occur without appending
        On Error Resume Next
        Application.CommandBars(strCBarName).Delete
        On Error GoTo 0
    
        ' Create a pop-up menu.
        Set cbrCmdBar = Application.CommandBars.Add(Name:=strCBarName, Position:=msoBarPopup)
    
        'DEFINE COMMAND BAR CONTROL
        With Application.CommandBars(strCBarName).Controls.Add(Type:=msoControlButton)
            .Caption = "MyMenu"
            .OnAction = "'MyProc ""A"",""B"",2'"
        End With
        Application.CommandBars(strCBarName).ShowPopup
    End Sub
    
    Sub MyProc(x As String, y As String, z As Integer)
        MsgBox x & y & (z * 2)
        Debug.Print "AHA!!! the breakpoint works, and it's only called once!!!!!!"
    End Sub
    

    The key is to call the procedure in the .OnAction event surrounded by single quotes. Also, you need to escape your double quotes with double quotes. Numeric parameters need not be escaped.

提交回复
热议问题