Okay so you've created a custom menu in Excel and you've wired up the menu items to your code. You've tested it and it works - first time. Click the menu item again however and nothing happens. Why not? Well, if you've used the code in my previous post (or something similar) then the menu items have gone out of scope after the first click. Arrrrggg! To prevent this, you have to create a class level property to hold your menu items, like so...

const string MENU_CAPTION = "MyTestMenu";
Office.CommandBarButton XmlFormLoadermenuItem;
Office.CommandBarButton FormulaWalkerFormmenuItem;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    //GS - Get a hold of the menubar
    Office.CommandBarControls cbc =
        this.Application.CommandBars[1].Controls;

    //GS - Create a new menu for our addin to use
    Office.CommandBarPopup newMenu =
        (Office.CommandBarPopup)cbc.Add(
            Office.MsoControlType.msoControlPopup, Type.Missing,
                Type.Missing, cbc.Count, true);

    //GS - Give the menu a sensible caption
    newMenu.Caption = MENU_CAPTION;

    //GS - Add a menu item to open the Xml input loader form
    XmlFormLoadermenuItem =
        (Office.CommandBarButton)newMenu.Controls.Add(
            Office.MsoControlType.msoControlButton,
                Type.Missing, Type.Missing, Type.Missing, true);

    //GS - Caption the menu item
    XmlFormLoadermenuItem.Caption = "Item 1...";
    XmlFormLoadermenuItem.Tag = "1";

    //GS - Wire up the click event
    XmlFormLoadermenuItem.Click += new Office.
        _CommandBarButtonEvents_ClickEventHandler(
            XmlFormLoadermenuItem_Click);

    //GS - Add a menu item to open the formula walker form
    FormulaWalkerFormmenuItem =
        (Office.CommandBarButton)newMenu.Controls.Add(
            Office.MsoControlType.msoControlButton,
                Type.Missing, Type.Missing, Type.Missing, true);

    //GS - Caption the menu item
    FormulaWalkerFormmenuItem.Caption = "Item 2...";
    FormulaWalkerFormmenuItem.Tag = "2";

    //GS - Wire up the click event
    FormulaWalkerFormmenuItem.Click +=
        new Office._CommandBarButtonEvents_ClickEventHandler(
            FormulaWalkerFormmenuItem_Click);
}
Technorati Tags: , ,