Sometimes you need to send your workbook out into the world with specific worksheets protected. If you find that you’re constantly protecting and unprotecting sheets before distributing your work-books, this macro can help you.
Private Sub Workbook_BeforeClose(Cancel As Boolean) 'Step 1: Protect the sheet with a password Sheets("Sheet1").Protect Password:="ExcelHowTo" 'Step 2: Save the workbook ActiveWorkbook.Save End Sub
How This Macro Works
This code is triggered by the workbook’s BeforeClose event. When you try to close the workbook, this event fires, running the code within. The macro automatically protects the specified sheet with the given password, and then saves the workbook.
- In Step 1, we are explicitly specifying which sheet we want to protect — Sheet1, in this case. We are also providing the password argument,
Password:="ExcelHowTo". This defines the password needed to remove the protection.This password argument is completely optional. If you omit this altogether, the sheet will still be protected, but you won’t need a password to unprotect it. Also, be aware that Excel pass-words are case-sensitive, so you’ll want pay attention to the exact password and capitalization that you are using.
- Step 2 tells Excel to save the workbook. If we don’t save the workbook, the sheet protection we just applied won’t be in effect the next time the workbook is opened.when a user attempts to modified such a protected cell, Excel would displaying a message telling the user:
"the cell or chart you are trying to change is protected and therefore read-only..."
How to Use This Macro
To implement this macro, you need to copy and paste it into the Workbook_BeforeClose event code window. Placing the macro there allows it to run each time you try to close the workbook.
- Activate the Visual Basic Editor by pressing
- In the Project window, find your project/workbook name and click the plus sign next to it in order to see all the sheets.
- Click ThisWorkbook.
- Select the BeforeClose event in the Event drop-down list.
- Type or paste the code in the newly created module, modifying the sheet name (if necessary) and the password. Note that you can protect additional sheets by adding additional statements before the