我正在尝试通过VBA打开一个Excel(xlsm)文件。它可能使用(或已知的)密码来保护也可能不受保护。我正在使用以下代码:
On Error Resume Next Workbooks.Open filename,Password:= user_entered_pw 打开=(Err.Number = 0)错误转到0现在,这个如果工作簿有密码,工作正常。但如果没有保护,则无法打开。显然这是XL2007中的一个错误,如果还有工作簿结构保护激活。 ( vbaadventures.blogspot/2009 /01/possible-error-in-excel-2007.html )。在旧的XL2003上,提供密码将打开无保护和密码保护的文件。
我试过:
Workbooks.Open filename,Password:= user_entered_pw If(Err.Number<> 0)Then workbooks.open filename pre>这适用于未受保护和受保护的文件。但是,如果用户输入错误的密码,它将进入第二行,弹出输入密码提示,这不是我想要的。
如何解决这个问题?
解决方案为了纪录 - 原因确实是我正在开放的工作簿的结构保护。 我可以通过禁用结构保护来规避问题,并在Workbook_Open()(在受保护的工作簿中)重新保护。
结构保护无效,即使没有密码, Workbooks.Open 与密码也不会失败。 p>
由于我通过VBA方法打开,VBA代码已经被信任,意味着一定会调用Workbook_Open方法。
I am trying to open an Excel (xlsm) file via VBA. It may or may not be protected with a (known) password. I am using this code:
On Error Resume Next Workbooks.Open filename, Password:=user_entered_pw opened = (Err.Number=0) On Error Goto 0Now, this works fine if the workbook has a password. But if it is unprotected, it can NOT be opened. Apparently this is a bug in XL2007 if there is also workbook structure protection active. (vbaadventures.blogspot/2009/01/possible-error-in-excel-2007.html). On old XL2003, supplying a password would open both unprotected and password protected file.
I tried:
Workbooks.Open filename, Password:=user_entered_pw If (Err.Number <> 0) Then workbooks.open filenameThis works for unprotected and protected file. However if the user enters a wrong password it runs into the second line and pops up the "enter password" prompt, which I do not want.
How to get around this?
解决方案For the record - the reason was indeed the structure protection of the workbook I was opening. I could circumvent the problem by disabling structure protection, and re-protecting in Workbook_Open() (in the protected workbook).
With structure protection inactive, Workbooks.Open with password does not fail even when there is no password.
Since I am opening via a VBA method, the VBA code is already trusted, meaning the Workbook_Open method will surely be called.
更多推荐
检查Excel文件是否受密码保护
发布评论