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.

Thanks
HideRows-As-Per-Dropdown-Selection-.xlsm
cesemjAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
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
    Else
        Sheets("Checklist").Rows("4:6").EntireRow.Hidden = False
    End If
End If
Sh.Protect Password:=MyPassword
Application.ScreenUpdating = True
Sh.Activate
End Sub

Open in new window

HideRows-As-Per-Dropdown-Selection_.xlsm
0
 
cesemjAuthor Commented:
Thanks I will try and let you know.
0
 
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.
Run-Macro-On-Protected-Sheet.xlsm
0
 
cesemjAuthor Commented:
Thank you both.  Such tremendous value you insight is.  Thanks.
0
 
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!
0
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.