How can we disable delete and rename option of the context menu of excel at the sheet level
My requirement is that, I need to disable the Delete and Rename option at the sheet level and not at the overall application/wo开发者_C百科rkbook level.
I have done the below in the ThisWorkbook_Startup event of the Workbook.cs file
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Delete"].Enabled = false;
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Rename"].Enabled = false;
But this code is applicable at the overall workbook level. Say I want to perform the same only for Sheet1 and not for other sheets.
How can we do it?
I am using Excel VSTO 2007 and C# is the language
Thanks
I found the answer. We need to invoke the method DisableContextMenuItems() from Workbook's Startup and SheetActivated Event.
Startup event will be called for the very first time when the Addin will be loaded. And for every sheet change or activated, the SheetActivate event will be fired.
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
DisableContextMenuItems();
}
void ThisWorkbook_SheetActivate(object Sh)
{
DisableContextMenuItems();
}
private static void DisableContextMenuItems()
{
var sheet = Globals.ThisWorkbook.ActiveSheet as ExcelXP.Worksheet;
var name = sheet.Name;
if (name != "Sheet1")
{
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Delete"].Enabled = true;
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Rename"].Enabled = true;
}
else
{
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Delete"].Enabled = false;
Globals.ThisWorkbook.Application.CommandBars["Ply"].Controls["&Rename"].Enabled = false;
}
}
Thanks
精彩评论