Skip to main content

How to: Protect a Worksheet

  • 2 minutes to read

You can protect a worksheet by locking cells, so that end-users can only perform a specific (restricted) set of actions specified by the WorksheetProtectionPermissions enumeration member.

By default, all cells in a worksheet have the Protection.Locked attribute set to true. When protection is applied to a worksheet, these cells become read-only. Cells with the Protection.Locked attribute set to false are not protected when worksheet protection is applied, so that the end-users can edit or delete their content.

To apply worksheet protection, use the Worksheet.Protect method, as illustrated in the example below. By default, when you pass the WorksheetProtectionPermissions.Default parameter to the Protect method, a protected worksheet is locked so that an end-user can only select cells.

View Example

Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;

// Protect the worksheet. Prevent end-users from changing worksheet elements.
if (!worksheet.IsProtected)
    worksheet.Protect("password", WorksheetProtectionPermissions.Default);
// Add a note.
worksheet["B2"].Value = "Worksheet is protected with a password. \n You cannot edit or format cells until protection is removed." +
                        "\nTo remove protection, on the Review tab, in the Changes group," +
                        "\nclick \"Unprotect Sheet\" and enter \"password\".";
worksheet.Visible = true;

Unprotect a Worksheet

To remove protection, use the Worksheet.Unprotect method.

View Example

Worksheet worksheet = workbook.Worksheets("ProtectionSample");
workbook.Worksheets.ActiveWorksheet = worksheet;

// Remove worksheet protection using a password.
if (worksheet.IsProtected) {
    worksheet.Unprotect("password");
}
// Add a note.
worksheet("B2").Value = "Worksheet is unprotected. You can edit and format cells.";
worksheet.Visible = true;
See Also