MS-Excel / General Formatting

Auto-Toggle Worksheet Protection

This method dynamically turns worksheet protection on and off, but will also enable you to use all of Excel's features when you are in a cell that is not locked.

To start, ensure that only the cells you want protected are locked and that all other cells are unlocked.

Right-click the Sheet Name tab, select View Code from the pop-up menu, and enter the following code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Locked = True Then
Me.Protect Password:="Secret"
Else
Me.Unprotect Password:="Secret"
End If
End Sub

If no password is used, omit Password:="Secret". If a password is used, change the word Secret to your password. Press Alt-Q or click the X in the top-righthand corner to get back to Excel and save your workbook.

If you're worried about your users getting into the macro and disabling it, you can password-protect your macro by selecting Tools → VBAProject Properties, going to the Protection tab, selecting "Lock Project for Viewing", and entering a password.

Now, each time you select a cell that is locked, your worksheet will automatically protect itself. The moment you select any cell that is not locked, your worksheet will unprotect itself.

[Previous] [Contents]

In this tutorial:

  1. Lock and Protect Cells Containing Formulas
  2. Locking Formula Cells
  3. Data Validation
  4. Auto-Toggle Worksheet Protection