Skip to main content

How to: Protect a Workbook

  • 2 minutes to read

The example below demonstrates how to protect an entire workbook by using the Workbook.Protect method. Workbook protection prevents end-users from modifying a workbook structure (by moving, deleting, adding, renaming, or hiding existing worksheets, or displaying hidden sheets).

View Example

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

// Protect workbook structure with the password (prevent users from adding or 
//deleting worksheets or displaying hidden worksheets).
if (!workbook.IsProtected)
    workbook.Protect("password", true, false);
// Add a note.
worksheet["B2"].Value = "Workbook structure is protected with a password. \n You cannot add, move or delete worksheets until protection is removed.";
worksheet.Visible = true;

Unprotect a Workbook

To remove protection, use the Workbook.Unprotect method.

View Example

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

// Unprotect the workbook using a password.
if (workbook.IsProtected)
    workbook.Unprotect("password");
// Add a note.
worksheet["B2"].Value = "Workbook is unprotected. Workheets can be added, moved or deleted.";
worksheet.Visible = true;
See Also