Learn

Macro 4: Protect a Worksheet on Workbook Close

Macro 4: Protect a Worksheet on Workbook Close

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.

How it 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.

Private Sub Workbook_BeforeClose(Cancel As Boolean)

‘Step 1: Protect the sheet with a password

Sheets(“Sheet1″).Protect Password:=”RED”

‘Step 2: Save the workbook

ActiveWorkbook.Save

End Sub

1. 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:=RED. 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 capitaliza-

tion that you are using.

2. 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.

How to use it

To implement this macro, you need to copy and paste it into the Workbook_BeforeClose event

code window. Placing the macro here allows it to run each time you try to close the workbook.

1. Activate the Visual Basic Editor by pressing ALT+F11.

2. In the Project window, find your project/workbook name and click the plus sign next to it in

order to see all the sheets.

3. Click ThisWorkbook.

4. Select the BeforeClose event in the Event drop-down list (see Figure 2-4).

5. 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 state-

ments before the ActiveWorkbook.Save statement.

Figure 2-4: Type or paste your code in the Workbook_BeforeClose event code window.

learn
We will be happy to hear your thoughts

Leave a reply

Share knowledge
Learn
Logo
Enable registration in settings - general