Search code examples
c#office-interopribbonexcel-addins

Load excel Ribbon on demand


I would like to add functionality to my Excel addin so I could load different Ribbons on demand.

At the moment I am trying by exporting the ribbon to XML and loading it

private Microsoft.Office.Core.IRibbonExtensibility ribbonObj;
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
    DialogResult RibbonToLoad = MessageBox.Show("Yes = V2  No = V3", "Select Version", MessageBoxButtons.YesNo);
    switch (RibbonToLoad)
    {
        case DialogResult.Yes:
           ribbonObj = new RibbonV2();
           return ribbonObj;
        case DialogResult.No:
           ribbonObj = new RibbonV3();
           return ribbonObj;
     }

    return new RibbonV2();
}

The problema with this is I cannot find how to switch this Ribbon. I don't find it inside the Globals. object.

Also I tried without exporting to XML, but also I couldn't achieve the load on demand of a different ribbon while running(e.g. clicking a button on a WPF window...)

Any idea how to get this? I would like to have the possibility of loading different ribbons on the same addin(but only one would be present at once)


Solution

  • You can't manage the process of loading ribbon controls. But you can change visibility of your controls at runtime. The IRibbonUI interface provides the Invalidate and InvalidateControl methods that allow to trigger your callbacks where you can change visibility at runtime (getVisible).

    In the following example, starting the host application triggers the onLoad event procedure that then calls a procedure which creates an object representing the Ribbon UI. Next, a callback procedure is defined that invalidates all of the controls on the UI and then refreshes the UI.

    The following is the XML markup for Office to load the custom ribbon:

    <customUI … onLoad=”MyAddInInitialize” …>
    

    The following is the callback method for the onLoad event:

    Dim MyRibbon As IRibbonUI
    
    Sub MyAddInInitialize(Ribbon As IRibbonUI)
        Set MyRibbon = Ribbon
    End Sub
    
    Sub myFunction()
        ‘ Invalidates the caches of all of this add-in’s controls 
        MyRibbon.Invalidate()            
    End Sub
    

    You can read more about the Ribbon UI in the following series of articles in MSDN: