How to set password when someone clicks on unprotectsheet in excel and create a button for editing

后端 未结 1 1231
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 10:46

I have locked cells in a spreadsheet using this lines of code.

Range(\"A1:D23\").Select
Selection.Locked = True
ActiveSheet.Protect Contents:=True
相关标签:
1条回答
  • 2021-01-28 11:18

    I get the first part of your question. You need to specify a password argument as part of the worksheet's Protect method:

    Sub lockSheet()
        With ActiveSheet
    
            'Check sheet is not already protected
            If Not .ProtectContents Then
    
                'Clear any existing lock settings
                .Cells.Locked = False
    
                .Range("A1:D23").Locked = True
                .Protect Contents:=True, Password:="pw"
            End If
        End With
    End Sub
    

    Note that it is not necessary to select a range before modifying it, simply apply the action directly to the range.

    The password is obviously visible in plaintext, if you need to secure to any degree then you'll also need to apply a password to the VBA project.

    To address the second part of your question, as amended in your comment:

    Private Sub Worksheet_SelectionChange(ByVal target As Range)
        If target.Locked Then
            With ActiveSheet
                .Unprotect
                If Not .ProtectContents Then
                    target.Locked = False
                    .Protect Contents:=True, Password:="pw"
                End If
            End With
        End If
    End Sub
    

    This would need added to the worksheet module.

    0 讨论(0)
提交回复
热议问题