我明白你问题的第一部分。您需要将密码参数指定为工作表参数的一部分
Protect
方法:
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
请注意,在修改范围之前不必选择该范围,只需将操作直接应用于该范围即可。
apply a password to the VBA project
.
请回答您在评论中修改的问题的第二部分:
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