Identify which ribbon control was clicked from a macro (MS Word VBA)

时间:2016-02-12 20:44:22

标签: vba ms-word word-vba ribbon

I have several macros that all do near identical things: each one opens a separate file. I have them activated through controls on a customized ribbon. But instead of having several macros that look like this:

StackPanel stackPanel = new StackPanel();
CheckInfo check = selectedChecks[printItemIndex];
PrintCheck printCheck = BuildPrintCheck(check);
stackPanel.Children.Add(printCheck);
stackPanel.Measure(new Size(args.PrintableArea.Width, double.PositiveInfinity));
if (++printItemIndex < selectedChecks.Count) 
       args.HasMorePages = true;

args.PageVisual = stackPanel;

but with only the filename changed, I'd like to have one macro that can open any one document depending on which ribbon element was clicked. Problem is, I need to know the ID of the ribbon element that was clicked. I've been through several web sites that all suggest using the IRibbonUI.ID property, but when I try that, I get an error message from Word: "Runtime error 91: Object variable or With block variable not set."

Here's a sample of the exported XML code for my ribbon:

ChangeFileOpenDirectory SeriesPath
Documents.Open FileName:="Doc1.docx", _
    ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
    PasswordDocument:=Password$, PasswordTemplate:="", Revert:=False, _
    WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
    wdOpenFormatAuto, XMLTransform:=""

Does anyone know what I'm doing wrong?

1 个答案:

答案 0 :(得分:0)

First, please excuse any syntax errors, these answers are in psuedo vba/xml.

1) I would suggest using the id parameter of the ribbon control object to determine the callee, instead of using a different function. You could possibly rename them to something more clean such as:

elem.SubBranch

2) You can then 'parse' based on the ID, or just do a case/switch statement on the entire ID

idQ="x1:Open_00" label="00" ... onAction="Open_OnAction"
idQ="x1:Open_01" label="01" ... onAction="Open_OnAction"

*Note: If you wanted to be even more slick, you could put filename into the ID (via XML), and not even use a case statement, and parse it out. EG:

Sub Open_OnAction(control As IRibbonControl)
    Dim filename As String
    Select Case control.id
        Case "x1:Open_00"
            filename = "somefilename00.xml"
        Case "x1:Open_01"
            filename = "somefilename01.xml"
    End Select

    'The rest of your code here
End Sub