Worksheet protection set using ws.protect - but doesnt unprotect using the Menu (Review - Unprotect sheet)

大憨熊 提交于 2019-12-11 02:57:22

问题


I have the following code to protect the sheets of a workbook in Excel 2007

Private Sub password_protectallsheets()
For Each ws In Worksheets
ws.protect Password = "edc1"
Next
End Sub

but when I try to unprotect the sheet using the password through the Excel 2007 Menu (review -> Unprotect sheet), it says the password you have supplied is not correct.

Any help is hugely appreciated.


回答1:


Try:

Option Explicit

Private Sub password_protectallsheets()
    Dim ws As Worksheet
    For Each ws In Worksheets
        ws.Protect "edc1"
    Next
End Sub

without the password key argument.
It worked on my Excel 2007.

Btw, be sure you copy/paste the password or be sure to check if the last character is wether a 1 (one) or a l (lower-case letter L).




回答2:


The password argument needs to be specified with ":=" - not just "=". This is true for arguments to methods in general:

ws.protect Password := "edc1"

To have the compiler catch these types of errors, always use Option Explicit at the beginning of modules, as JMax has done above. When you do so, the compiler will give you a "Variable not Defined" error when you forget the ":" Option Explicit will save you lots of time with other types of variable declaration errors. To enable it for all new modules check Tools>Options>Edit>Require Variable Declaration in the VBE.

The part I can't figure out is why, in the code without the ":" a password is assigned at all. I would have expected the sheet to be protected, but without a password.




回答3:


Does the Ws.Unprotect really protect the worksheet? - surly it unprotects a worksheet it doesn't set the protection

to set the protection in a macro why not record protecting a worksheet and have a look at the code



来源:https://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu

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