Search code examples
xmlvbams-wordribbonoffice-2010

Is there a way to use VBA and XML to add a button to the Office 2010 Ribbon depending on a string in the file name?


I have done some quite extensive customisation to the Office 2010 ribbon in Microsoft Word, using a combination of XML, VBA - using the Custom UI Editor.

What I'm trying to establish is that if it's possible to add a button to the ribbon based on if there is a certain string found in the current file name. For example:

  • If fileName contains "PM" (probably using the InStr method)
  • Add button to ribbon

Any pointers, examples or articles would be much appreciated. I've done some digging but haven't been able to find an appropriate method yet.

I was hoping to use the Onload attribute in the XML to fire the relevant sub that detects the filename and manipulates the ribbon accordingly.

Many thanks in advance.


Solution

  • Yes. You can change the layout of the Ribbon with VBA during runtime.

    You will have to add the control in the customUI-xml, then add a getVisible-tag within the control that references a VBA-function - you can get the correct signature for the VBA-function from the Custom UI Editor. The function then returns a boolean, True if you want the control to show, and False if not. You can evaluate filename or anything else you want, then return the desired value.

    Example customUI:

    <button id="btnTest" label="Try me" imageMso="FileMarkAsFinal" size="large" supertip="I dare you!" getVisible="GetBtnTestVisible" />
    

    Example VBA:

    'Callback for btnTest getVisible
    Sub GetBtnTestVisible(control As IRibbonControl, ByRef returnedVal)
        'Evaluate and set returnedVal accordingly
        returnedVal = True  'Control visible
        returnedVal = False 'Control hidden
    End Sub