tags:

views:

40

answers:

1

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.

+1  A: 

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.

Lunatik
thanks for resolving the first part.In the second part, what I want to do is as follows.I have some readonly cells.When the user clicks on Unprotect Sheet and enters the correct password,he'll be able to edit it.Whichever cells he selects for editing,I want to provide a button to him dynamically around his cell to update those changes.It's like A1 has 100 ,B1 has 200, and C1 has 300.When he changes A1 to 200 ,C1 should change to 400 on the dynamic button I created.Does that make it clear.
gizgok
Still not completely understanding your requirements, however it would be better if you asked a separate question instead of discussing it here.
Lunatik
Chuck the second question....tell me if u can,how can I unprotect only the cell I selected..
gizgok
I'm getting an error argument not optional wat am I doing worng when I'm calling your second function
gizgok
Have you added it to the worksheet code module? It won't work in a standard module.
Lunatik