VBA editing cells in protected sheet

自古美人都是妖i 提交于 2021-02-05 09:24:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!