HOWTO: How do I add commands to Excel's right-mouse menu?
Reference: Q0045
Article last modified on 15-Feb-2008
The information in this article applies to:
- XLL+ for Visual Studio .NET - 3, 4.1, 4.2, 4.3.1, 5.0
- XLL+ for Visual Studio 6 - 3, 4.1, 4.2, 4.3.1, 5.0
- XLL+ for Visual Studio 2005 - 5.0
How do I add commands to Excel's right-mouse menu?
Issue
I want my commands to appear when the user right-clicks in a spreadsheet. How do I do it?
Summary
-
Call the Excel API directly, using
xlfAddCommand, to create the menu item. -
Call the Excel API directly, using
xlfDeleteCommand, to delete the menu item.
Example
The code below adds a command "My Context Menu Item" to the right-click menu when the add-in is opened, and removes it when the add-in is closed.
BOOL CContextMenuApp::OnXllOpenEx()
{
// Add an item to the context menu, just before "Paste"
static int xlfAddCommand = 153;
CXlOper xloItem;
xloItem.AllocArray(1, 2);
xloItem[0] = "&My Context Menu Item"; // Text of menu item
xloItem[1] = "MyAddinFunction"; // Name of macro function
CXllApp::Excel(xlfAddCommand, 4,
&CXlOper(7, 0),
&CXlOper(4, 0),
&xloItem,
&CXlOper("Paste")); // Menu item before which the new item will appear
return TRUE;
}
void CContextMenuApp::OnXllClose()
{
// Remove the item from the context menu
static int xlfDeleteCommand = 159;
CXllApp::Excel(xlfDeleteCommand, 3,
&CXlOper(7, 0),
&CXlOper(4, 0),
&CXlOper("&My Context Menu Item"));
}
