Export (0) Print
Expand All

How to: Add Commands to Shortcut Menus in Excel

This example demonstrates how to add a command to a shortcut menu in Excel by using an application-level add-in. The shortcut menu appears when you right-click a worksheet cell. When the end user clicks the command, the text contained in all selected cells is written to a text file.

Applies to: The information in this topic applies to document-level projects and application-level projects for Excel 2007 and Excel 2010. For more information, see Features Available by Office Application and Project Type.

Add the following code to the ThisAddIn class in an application-level add-in project for Excel.


private Office.CommandBarButton writeToText;
private Excel.Range selectedCells;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    DefineShortcutMenu();
    Application.SheetBeforeRightClick +=
        new Excel.AppEvents_SheetBeforeRightClickEventHandler
            (Application_SheetBeforeRightClick);
    writeToText.Click +=
        new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler
            (writeToText_Click);
}

void writeToText_Click(Office.CommandBarButton Ctrl,
    ref bool CancelDefault)
{
    try
    {
        System.DateTime currentDateTime = System.DateTime.Now;
        string dateStamp = currentDateTime.ToString("dMMMMyyyy_hh.mm.ss");

        string fileName =
            System.Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) + "\\\\" + dateStamp + ".txt";
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName);

        foreach (Excel.Range cell in selectedCells.Cells)
        {
            if (cell.Value2 != null)
            {
                sw.WriteLine(cell.Value2.ToString());
            }
        }
        sw.Close();
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
}
void Application_SheetBeforeRightClick(object Sh,
    Excel.Range Target, ref bool Cancel)
{
    selectedCells = Target;
}

private void DefineShortcutMenu()
{

    Office.MsoControlType menuItem = Office.MsoControlType.msoControlButton;
    writeToText = (Office.CommandBarButton)Application.CommandBars["Cell"].
        Controls.Add(menuItem, missing, missing, 1, true);

    writeToText.Style = Office.MsoButtonStyle.msoButtonCaption;
    writeToText.Caption = "Write to a Text File";
    writeToText.Tag = "0";
}


You must set the Tag property of your controls when you add event handlers. Office uses the Tag property to keep track of event handlers for a specific CommandBarControl. If the Tag property is blank, the events are not handled properly.

Declare your menu variables at the class level instead of inside the method where they are called. This ensures that the menu variables will remain in scope as long as the application is running. Otherwise, the item is removed by garbage collection, and your event handler code stops working.

Community Additions

ADD
Show:
© 2014 Microsoft