简体   繁体   English

excel vba通过测试多个密码来打开工作簿

[英]excel vba to open a workbook by testing multiple passwords

I have password-protected .xls files in a directory. 我在目录中有受密码保护的.xls文件。 I would like to open each of these files and save them without the password. 我想打开每个文件并保存它们而无需输入密码。

However, the files can be opened by using either of the sample passwords listed below. 但是,可以使用下面列出的任一示例密码来打开文件。

pwd1 = "123"
pwd2 = "456"
pwd3 = "789"

'Check if pwd1 opens
Application.Workbooks.Open(Filename:=fn, Password:=pwd1)

'If fail then use pwd2
Application.Workbooks.Open(Filename:=fn, Password:=pwd2)

'and so on..

How should I implement this? 我应该如何实施呢?

Once the file has been opened once, you only need to Unprotect it. 一旦文件被打开一次,您只需要Unprotect它。 This will save a lot of time, instead of constantly opening/closing workbooks. 这将节省大量时间,而不是不断打开/关闭工作簿。

Here's how I'd do it: 这是我的处理方式:

Public Sub CrackWorkbook()
    Dim fn As String
    fn = "C:\Temp\test_password_is_456.xlsx"

    Dim wb As Workbook
    Set wb = Workbooks.Open(fn)

    Dim lst As Variant
    lst = Array("123", "456", "789")

    Dim item As Variant
    For Each item In lst
        On Error GoTo did_not_work
        Call wb.Unprotect(item)
        Call wb.Save
        Call wb.Close(False)
        Exit Sub
did_not_work:
        On Error GoTo 0
    Next item
End Sub

In other words, create an array of strings and do a For Each on them, and set some error-handling to deal with all the failed attempts. 换句话说,创建一个字符串数组并对它们执行一个For Each ,并设置一些错误处理以处理所有失败的尝试。

I know GoTo statements are a bit yucky, but that's the best way to handle errors in VBA (as far as I know). 我知道GoTo语句有点麻烦,但这是处理VBA中错误的最佳方法(据我所知)。

I tried @lebelinoz answer however the routine gives a 1004 error. 我尝试了@lebelinoz答案,但是例程给出了1004错误。 I googled this behavior and found this post: https://stackoverflow.com/questions/21176638/vba-how-to-force-ignore-continue-past-1004-error 我用谷歌搜索了这种行为并找到了这个帖子: https : //stackoverflow.com/questions/21176638/vba-how-to-force-ignore-continue-past-1004-error

The code below works by using On Error Resume Next . 下面的代码通过使用On Error Resume Next I based this on @lebelinoz answer. 我基于@lebelinoz答案。

Public Sub CrackWorkbook()
Dim fn As String
fn = "C:\Temp\test_password_is_456.xlsx"

Dim wb As Workbook
Dim item As Variant
Dim lst As Variant

lst = Array("123", "456", "789")

For Each item In lst
    On Error Resume Next
    Workbooks.Open Filename:=fn, Password:=item
If Err.Number <> 0 Then GoTo did_not_work:
    Exit For

did_not_work:
    Next item
Set wb = Activeworkbook
wb.SaveAs Filename:=fn, Password:=""
wb.Close

End Sub

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

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