检查Excel文件是否受密码保护

编程入门 行业动态 更新时间:2024-10-24 06:34:05
本文介绍了检查Excel文件是否受密码保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过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 0

Now, 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 filename

This 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文件是否受密码保护

本文发布于:2023-11-10 15:53:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575801.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密码保护   文件   Excel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!