简体   繁体   English

Excel:保护密码与VBA密码不兼容?

[英]Excel: Protect password not compatible with VBA password?

I know of the 2 possible ways to password-protect sheets in Excel - 我知道在Excel中使用密码保护工作表的2种可能方法-

  1. Manual Password protect 手动密码保护
  2. Password protect using VBA 使用VBA进行密码保护

This is where I'm stumped. 这就是我感到难过的地方。 I have password-protected a sheet using VBA and then tried to unprotect it manually with the same password used in VBA. 我已经使用VBA对工作表进行了密码保护,然后尝试使用与VBA中使用的相同密码手动取消保护它。 But Excel throws an error saying that the password provided is incorrect. 但是Excel引发错误,提示提供的密码不正确。 I tried the opposite as well - Protected the file manually and then tried to unprotect using VBA providing the right password in the code; 我也尝试了相反的做法-手动保护文件,然后尝试使用VBA在代码中提供正确密码的情况下取消保护; same error. 同样的错误。 Any ideas why this is happening? 任何想法为什么会这样?

If I am understanding your question correctly, it happens because each password is protecting something different. 如果我正确理解了您的问题,则会发生这种情况,因为每个密码都在保护不同的东西。 They are not the same thing. 它们不是同一件事。 You can have a workbook that is not password protected but the VBA code is password protected. 你可以有没有密码保护,但VBA代码密码保护的工作簿。

After some analysis, I figured out what the issue is in my code - 经过分析,我发现了代码中的问题-

ActiveWorkbook.Protect Password = "xyz", Structure:=True, Windows:=False

The password option was assigned with an "=" sign instead of a ":=". 密码选项分配了“ =”符号,而不是“:=”。 This code still protects the sheet but with an empty password. 该代码仍然保护工作表,但密码为空。 When I use a similar Unprotect code like, 当我使用类似的Unprotect代码时,

ActiveWorkbook.Unprotect Password = "xyz"

the unprotect code is passing on an empty password. 取消保护代码传递了空密码。 Hence, if I try a manual password of "xyz" it throws an error. 因此,如果我尝试使用手动密码“ xyz”,则会引发错误。

The correct code that solves the issue is 解决该问题的正确代码是

ActiveWorkbook.Protect Password:= "xyz", Structure:=True, Windows:=False
ActiveWorkbook.Unprotect Password:= "xyz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM