Showing posts with label Protect Sheet. Show all posts
Showing posts with label Protect Sheet. Show all posts

Tuesday, September 13, 2022

To Protect and Unprotect Sheet with VBA Code

To protect worksheet from editing. 

  • Go to Review Tab and click at Protect Sheet.

  • Under Protect Sheet Key in Password and Tick allow user to do and click OK.

  • Key in password to reconfirm and click OK.


  • Done.

VBA code:

Option Explicit
Sub ProtectSheet()
    
    If ActiveSheet.ProtectContents = False Then
        With ActiveSheet
            .Protect Password:="abc123", AllowInsertingRows:=True, _
             AllowDeletingRows:=True, Contents:=True, _
             AllowFiltering:=True, Scenarios:=True
            .EnableSelection = xlUnlockedCells
        End With
    End If
    
End Sub

To Unprotect worksheet. 

  • Go to Review Tab and click at Unprotect Sheet.

  • Key in password and click OK.

  • Done.

VBA code:

Option Explicit
Sub UnprotectSheet()
    
    If ActiveSheet.ProtectContents = True Then
        ActiveSheet.Unprotect Password:="abc123"
    End If
    
End Sub

Microsoft Reference - Protect Worksheet

Practice makes perfect. Thank You.