Master Master - 1 month ago 16x
C# Question

Making Changes to multiple excel worksheets programatically

at the moment my excel file has two sheets. A sheet titled "English" and a sheet titled "French".


I programmatically open my workbook and edit my english sheet without any issues. When I open my second sheet, I get presented with this follow error.

The cell or chart you're trying to change is on a protected sheet. To make a change, unprotect the sheet. You might be requested to enter a password.
May I ask how abouts should I be editing my second sheet.

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Workbook wb = excel.Workbooks.Open(fileLocation);

ws1.Range["E5"].Value = StartDate;
ws1.Range["G5"].Value = EndDate;

Worksheet ws = wb.Worksheets.get_Item("French");

ws.Range["E5"].Value = StartDate; // <- Crashes here
ws.Range["G5"].Value = EndDate;


Your worksheet is protected, so you'll need to unprotect it before modifying it.

Worksheet ws = wb.Worksheets.get_Item("French");

// Check for protection and unlock the worksheet
If ws.ProtectContents {


ws.Range["E5"].Value = StartDate;  // <- Crashes here
ws.Range["G5"].Value = EndDate;

If you don't know the password, you can brute-force it easily on old Excel files using the code in this question (you'll have to port it to C#, but that should be trivial). For Excel 2013 onwards, be aware of the problem being raised in that question, because brute-forcing no longer works.

You might want to reprotect the sheet afterward (otherwise you've significantly changed the structure of the file by removing the protection that someone decided to put on the worksheet. To do that, you'll want to use Worksheet.Protect. Probably you'll want to save the old protection parameters like Worksheet.ProtectContents, Worksheet.ProtectData, Worksheet.ProtectDrawingObjects, Worksheet.ProtectFormatting, and Worksheet.ProtectionMode so that you can reprotect it in the same way. If you're using the password cracker instead of knowing the password, you can also grab the cracked password from the routine and use that as the Password argument to the Worksheet.Protect method. This will seamlessly set the protection back to the way it was before.