Skip to main content

Excel Macro: 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 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

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.

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

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:

  1. Activate the Visual Basic Editor by pressing ALT + F11.
  2. Right-click the project/workbook name in the Project Window.
  3. Choose Insert -> Module.
  4. 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.
  5. Click Run button on the Visual Basic Editor toolbar.
  6. For more information, learn this course: Programming with Excel VBA

Leave a comment

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

Format your code: <pre><code class="language-vba">place your code here</code></pre>

  1. AV

    what if i want to protect all the sheets in workbook?

    • EX

      @avinash protect workbook with password 123:

      ActiveWorkbook.Protect Password:="123", Structure:=True, Windows:=False