gizgok
gizgok

Reputation: 7649

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

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

Range("A1:D23").Select
Selection.Locked = True
ActiveSheet.Protect Contents:=True

This prompts me whenever I click on a cell which is readonly to unprotect sheet from review tab and might be prompted for password.

My problem is, it is not prompting for password.How do I first set password when he wants to unprotect.Secondly I want to pass the row information that he selected to change and want to create a button when the adjoining readonly cell is used for editing.

Upvotes: 0

Views: 2936

Answers (1)

Lunatik
Lunatik

Reputation: 3948

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.

Upvotes: 1

Related Questions