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.
Protect a Worksheet Before Workbook Close
'------------------ ThisWorkbook ------------------ Private Sub Workbook_BeforeClose(Cancel As Boolean) 'Step 1: Protect the sheet with a password Sheets("Sheet1").Protect Password:="ExcelBaby" '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:="ExcelBaby". 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're trying to change is on a protected sheet. To make a change, unprotect the sheet. You might be requested to enter a password.
How to Use This Macro
Most VBA code should be placed in Standard Modules unless specified.
If you see a comment
'------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?
The following steps teach you how to put VBA code into a Standard Module:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA