Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Check whether Excel file is Password protected

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. (http://vbaadventures.blogspot.com/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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...