问题
I have protected a workbook using vba code. I would also like to let the user entering some values in the specific cells (n4, p7:p10).
I have tried by using the following code but it doesn't work. A pop-up error message mentions "Error 1004".
Range ("n4,p7:p10").select
Selection.locked=false
回答1:
Const wsPass As String = "Password123" '//Change to your password
For Each ws In ThisWorkbook.Sheets
ws.Unprotect wsPass
ws.Range("N4, P7:P10").Cells.Locked = False
ws.Protect wsPass
Next ws
Just a further note - you can protect the sheet in VBA to lock it from the user, but still allow programmatic access (e.g. using a macro) by using the user interface option:
Sheets("RandomWorksheet").Protect Password:="Password123", UserInterfaceOnly:=True
This would negate the need for any "unprotect" macro as your code would still run without hindrance.
回答2:
If the sheet is protected you can unprotected it in your code. This is what I normally use.
Dim protect As Boolean
protect = False
If ActiveSheet.ProtectContents Then
protect = True
ActiveSheet.Unprotect Password:="password"
End If
Range ("n4,p7:p10").select
'Selection.locked=false
If Not (ActiveSheet.ProtectContents) And protect = True Then
ActiveSheet.protect Password:="password"
End If
Just make sure you change password to your password
来源:https://stackoverflow.com/questions/28499652/vba-editing-cells-in-protected-sheet