简体   繁体   中英

Lock and unlock sheet via VBA coding

I've modified a VB code to show and hide rows based on the value of a cell. The code works well, but I need to password protect the sheet, and of course once the sheet is protected the VB won't run.

I've tried a few variations but I'm not a programmer so I'm just not getting it - could someone smarter please help me out?

Code as below:

Private Sub Worksheet_Change(ByVal Target As Range)

 Rows("1:" & Rows.Count).EntireRow.Hidden = False

 If Range("M11") = "0" Then
 Rows("13:92").EntireRow.Hidden = True

End If
 
 If Range("M11") = "Mini" Then
 Rows("13:18").EntireRow.Hidden = True
 Rows("38:57").EntireRow.Hidden = True
 
 End If

 If Range("M11") = "Small" Then
 Rows("13:18").EntireRow.Hidden = True
 Rows("43:57").EntireRow.Hidden = True
 
 End If

 If Range("M11") = "Standard" Then
 Rows("13:18").EntireRow.Hidden = True

 End If
 
End Sub

I tried variations of unlock code, but I don't know enough about programming to know how it all fits together, so I just get errors.

Unprotect, hide/unhide based on the cell value, then re-protect.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Me.Range("M11")) Is Nothing Then Exit Sub

    Me.Unprotect Password:="YourPasswordHere"
    Me.Rows.Hidden = False

    Select Case Me.Range("M11").Value
        Case 0
             Me.Rows("13:92").Hidden = True
        Case "Mini"
             Me.Rows("13:18").Hidden = True
             Me.Rows("38:57").Hidden = True
        Case "Small"
             Me.Rows("13:18").Hidden = True             
             Me.Rows("43:57").Hidden = True
        Case "Standard"
             Me.Rows("13:18").Hidden = True
    End Select

    Me.Protect Password:="YourPasswordHere"
End Sub

As mentioned in the comments, another option is to Protect the sheet using UserInterfaceOnly:=True . With this method, you'll need to leverage the Workbook_Open event to protect the sheet. UserInterfaceOnly does not persist if the workbook is closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM