Search code examples
c#excelinteropspreadsheet-protection

How do I set locked cell protection options in Excel with C# and Interop?


Here's the background info. I have an app that writes to an excel 2007 .xlsm file and I am using C# and the Excel 12.0 interop object libraries to do it, along with Visual Studio 2010. I am able to change the cell values and formulas, set the font and font style, set the cells to locked or not, etc. The last thing I need to do is to set the protection of the sheet to disallow selection of locked cells.

When I try to call this code, as a test of general sheet protection...

((Excel.Worksheet)excelApp.ThisWorkbook.Sheets[0]).Protect(Password: protectionPassword, AllowFormattingCells: false);

...I get the exception Exception from HRESULT: 0x800A03EC telling me a COM Exception was unhandled.

Also, the interop Protection object does not give me the option that I mentioned above, although that option is available in excel when I click "Protect Sheet" under the review tab.

So, now my question: How do I protect the desired sheet in Excel with with the option to AllowSelectLockedCells turned off using Excel Interop in C#?


Solution

  • You've probably solved this since it was asked, but for the benefit of those (such as me) who stumble upon this from search engines hoping for a solution:

    Three points to get this working:

    • _Application.ThisWorkbook actually refers to the workbook object that contains macros, not the currently-active workbook in an Excel instance. For that you need _Application.ActiveWorkbook.
    • Excel worksheet indexes begin at 1, not 0.
    • To prevent locked cells from being selected (the AllowSelectLockedCells you were looking for) you first set the EnableSelection property to XlEnableSelection.xlUnlockedCells before locking the sheet.

    So the following will do what you need:

    ((Excel.Worksheet)excelApp.ActiveWorkbook.Sheets[1]).EnableSelection = Excel.XlEnableSelection.xlUnlockedCells;
    ((Excel.Worksheet)excelApp.ActiveWorkbook.Sheets[1]).Protect(Password: protectionPassword, AllowFormattingCells: false);