Export (0) Print
Expand All

How to: Programmatically Protect Worksheets

The protection feature in Microsoft Office Excel helps prevent users and code from modifying objects in a worksheet. By default, all cells are locked after you turn on protection.

Applies to: The information in this topic applies to document-level projects and application-level projects for Excel 2013 and Excel 2010. For more information, see Features Available by Office Application and Project Type.

In document-level customizations, you can protect worksheets by using the Excel designer. You can also protect a worksheet programmatically at run time in any project type.

Note Note

You cannot add Windows Forms controls to areas of a worksheet that are protected.

To protect a worksheet in the designer

  • In the Changes group of the Review tab, click Protect Sheet.

    The Protect Sheet dialog box appears. You can set a password and optionally specify certain actions that users are allowed to perform with the worksheet, such as format cells or insert rows.

You can also allow users to edit specific ranges in protected worksheets.

To allow editing in specific ranges

  • In the Changes group of the Review tab, click Allow Users to Edit Ranges.

    The Allow Users to Edit Ranges dialog box appears. You can specify ranges that are unlocked using a password, and users who can edit ranges without a password.

The following code sets the password (using the variable getPasswordFromUser, which contains a password obtained from the user) and allows only sorting.

To protect a worksheet by using code in a document-level customization

  • Call the Protect method of the worksheet. This example assumes that you are working with a worksheet named Sheet1.

    Globals.Sheet1.Protect(getPasswordFromUser, true);
    

To protect a worksheet by using code in an application-level add-in

  • Call the _Worksheet.Protect method of the active worksheet.

    ((Excel.Worksheet)Application.ActiveSheet).Protect(getPasswordFromUser, true);
    
Show:
© 2014 Microsoft