Search code examples
vbams-wordkeyboard-shortcutsribbonx

Simulate, through a macro, a click on a custom ribbon item


I've seen similar questions asked, but did not manage to find an answer to my specific problem.

I have in place a custom ribbon tab, with custom buttons. Their purpose is to each insert a QuickPart in the document.

As I have a lot of different QuickParts to be inserted, I didn't want to create a macro for each and every one.

So, when a user select an item in the ribbon, a single macro is called on, which uses the control.ID property to insert the appropriate QuickPart.

Everything works well, but now I'm asked to add keyboard shortcuts for some of these ribbon items.

Here's what I have until now:

  1. The macro that inserts QuickParts:

    Sub TalkToRibbon(control As IRibbonControl)    
        ...    
    End Sub
    
  2. When a shortcut is pressed, this macro is triggered:

    Sub interac_obj_cart()    
        shortcut = "interac_obj_cart"
        TalkToRibbon(shortcut)
    End Sub
    

Whether I define "shortcut" as a String or as a IRibbonControl, I get error messages (albeit different). I feel like there is something I am missing. Thanks in advance for your help


Solution

  • Use keytips for ribbon controls instead of inventing something new. KeyTips are the keyboard shortcuts that appear on the Ribbon when you press the ALT key. You can assign your own KeyTips by using the keytip and getKeytip attributes. The getKeyTip callback has the following signature:

    C#: string GetKeytip(IRibbonControl control)
    
    VBA: Sub GetKeytip (control As IRibbonControl, ByRef label)
    
    C++: HRESULT GetKeytip ([in] IRibbonControl *pControl, [out, retval] BSTR *pbstrKeytip)
    
    Visual Basic: Function GetKeytip (control As IRibbonControl) As String
    

    The KeyTip is displayed when the user presses the ALT key plus one to three letters.

    Otherwise you need to refactor your code by extracting the handler into a separate function which accepts a controls ID and which can be called by others passing a control ID. For example:

    Sub TalkToRibbon(control As IRibbonControl)    
        Call EventHandlerWhichAcceptsID  control.ID   
    End Sub
    

    And then your keyboard shortcut handler could call it as well.