I have locked cells in a spreadsheet using this lines of code.
Range(\"A1:D23\").Select
Selection.Locked = True
ActiveSheet.Protect Contents:=True
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.