VBA Code does not function when the worksheets are password protected.

Hi and thanks in advance:

The spreadsheet hides-rows-on-one-spreadsheet-based-on-data-selected on the Source worksheet cell B4 .   When I protected the code stopped working.  Please suggest a way to allow the code to work and still protect the worksheets.

Who is Participating?

Improve company productivity with a Business Account.Sign Up

ShumsConnect With a Mentor Distinguished Expert - 2017Commented:
Try below, change your password accordingly in vba code as well in sheet protection.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Sh As Worksheet
Dim MyPassword As String
Set Sh = Sheets("Checklist")
MyPassword = "test123"
Application.ScreenUpdating = False
Sh.Unprotect Password:=MyPassword

If Target.Address = "$B$4" Then
    If Range("B4") = "Moderate" Or Range("B4") = "Low" Then
        Sheets("Checklist").Rows("4:6").EntireRow.Hidden = True
        Sheets("Checklist").Rows("4:6").EntireRow.Hidden = False
    End If
End If
Sh.Protect Password:=MyPassword
Application.ScreenUpdating = True
End Sub

Open in new window

cesemjAuthor Commented:
Thanks I will try and let you know.
Roy CoxConnect With a Mentor Group Finance ManagerCommented:
The code can be much simpler

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    Const PW As String = "secret"
''/// assumes password is secret, change to whatever you want
    With Sheets("Checklist")
        If .ProtectContents Then .Unprotect PW
        If Target.Address = "$B$4" Then
            .Rows("4:6").EntireRow.Hidden = Range("B4") = "Moderate" Or Range("B4") = "Low"
        End If
        .Protect PW
    End With
End Sub

Open in new window

Or use ProtectWithUserInterFace only which allows macros to run on protected sheets, see the attached example.
cesemjAuthor Commented:
Thank you both.  Such tremendous value you insight is.  Thanks.
Roy CoxGroup Finance ManagerCommented:
Sorry, but how can you award assist when I offered two more efficient methods. Maybe you consider unnecessary lines of code an advantage!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.