Home » excel » c# – Protect UserInterfaceOnly and EnableOutlining

c# – Protect UserInterfaceOnly and EnableOutlining

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am creating an addin for Excel. It is protecting the sheets in the workbook:

public static void ProtectSheetUi(_Worksheet sheet, string password)
{
    sheet.EnableOutlining = true;
    sheet.Protect(password, Contents: true, UserInterfaceOnly: true, AllowFormattingCells: true,
        AllowFormattingColumns: true, AllowFormattingRows: true);
}

But the problem is that when I close and reopen the workbook, grouping/ungrouping doesn’t work. This is because UserInterfaceOnly is not persistent.
In the workbook level, I could unprotect and protect the sheets again when it is being opened. But how can achieve this with an add-in?

How to&Answers:

The UserInterfaceOnly setting is not saved when you close the workbook. You will have to reset it when the workbook is opened. The best place to do this is in the Workbook_Open event procedure. So you need to handle that in your Add-In. For example (Doing this from memory so please ignore the typos/syntax errors)

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    this.Application.WorkbookOpen += 
    new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
}

void Application_WorkbookOpen(Excel.Workbook Wb)
{
   //~~> Rest of your code
}