Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 39
  • Last Modified:

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
0
cesemj
Asked:
cesemj
  • 2
  • 2
2 Solutions
 
ShumsAsst. Financial ControllerCommented:
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 CoxGroup 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

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now