Protect a Worksheet Before 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 can help you.

Macro Code

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

  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:="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.
  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.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.

  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.Workbook BeforeClose Event
  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 statements before the ActiveWorkbook.Save statement.

Leave a Reply

Your email address will not be published. Required fields are marked *