How to: Protect Workbooks
Applies to |
---|
The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office. Project type
Microsoft Office version
For more information, see Features Available by Application and Project Type. |
You can protect a Microsoft Office Excel workbook so that users cannot add or delete worksheets, and also unprotect the workbook programmatically. You can optionally specify a password, indicate whether you want the structure protected (so users cannot move sheets around), and indicate whether you want the workbook's windows protected.
Protecting a workbook does not stop users from editing cells. To protect the data, you must protect the worksheets. For more information, see How to: Protect Worksheets.
The following code examples use a variable to contain a password that is obtained from the user.
Protecting a Workbook That Is Part of a Document-Level Customization
To protect a workbook
Call the Protect method of the workbook and include a password. To use the following code example, run it in the ThisWorkbook class, not in a sheet class.
Me.Protect(getPasswordFromUser)
this.Protect(getPasswordFromUser, missing, missing);
To unprotect a workbook
Call the Unprotect method, passing a password if it is required. To use the following code example, run it in the ThisWorkbook class, not in a sheet class.
Me.Unprotect(getPasswordFromUser)
this.Unprotect(getPasswordFromUser);
Protecting a Workbook by Using an Application-Level Add-In
To protect a workbook
Call the Protect(Object, Object, Object) method of the workbook and include a password. This code example uses the active workbook. To use this example, run the code from the ThisAddIn class in your project.
Me.Application.ActiveWorkbook.Unprotect(getPasswordFromUser)
this.Application.ActiveWorkbook.Protect(getPasswordFromUser, missing, missing);
To unprotect a workbook
Call the Unprotect(Object) method of the active workbook, passing a password if it is required. To use this example, run the code from the ThisAddIn class in your project.
Me.Application.ActiveWorkbook.Protect(getPasswordFromUser)
this.Application.ActiveWorkbook.Unprotect(getPasswordFromUser);
See Also
Tasks
How to: Set and Clear Workbook Passwords
Concepts
The Variable missing and Optional Parameters in Office Solutions
Change History
Date |
History |
Reason |
---|---|---|
July 2008 |
Added a code example that can be used in an application-level add-in. |
Customer feedback. |