在vba循环中使用密码打开Excel文件

时间:2019-02-28 16:41:21

标签: excel vba

我有一个循环,该循环从100多个工作簿中抓取数据。有些具有工作簿和工作表的密码保护。

我以为我已经添加了用于输入每个工作簿密码的代码,并且一直有效,直到我更改代码以查看文件夹及其子文件夹(而不是单个文件夹),但是现在所有带有密码的文件都给出了密码。弹出输入密码。

我认为我没有在正确的位置输入密码。我已经尝试过将其移动到“对于每个OFile”等位置之前,但是在设置“ wb”而不给出任何错误之前,我不确定该怎么做。

任何帮助将不胜感激!

Sub Test_Macro()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim fso, oFolder, oSubfolder, OFile, queue As Collection
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("D:\example\example")
'^^^ UPDATE THIS FILE PATH TO FOLDER WHERE THE RETURNED SCORECARDS ARE STORED.

Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder
Next oSubfolder

For Each OFile In oFolder.Files

y = ThisWorkbook.Sheets("Consol").Cells(Rows.Count, 1).End(xlUp).Row + 1 '<<< Finda next available row containing a value in consol sheet

Set wb = Workbooks.Open(OFile.path) '<<< Sets variable to the open performance scorecard and unprotects
wb.Password = "Password" '<<<<This is one that doesn't appear to be working

Set ws = wb.Sheets("Detailed Summary") '<<< Defines sheet in the open scorecard to scrape from

ws.Unprotect Password:="Password"

wsLR = ws.Columns("B").Find("*", after:=ws.Cells(1, 2), SearchDirection:=xlPrevious, SearchOrder:=xlByRows, LookIn:=xlValues).Row '<<< Defines the range containing data in the open scorecard
Dim scraped As Variant
With ws
scraped = .Range(.Cells(5, 2), .Cells(wsLR, 85))
End With

Dim consolRng As Range
Set consolRng = ThisWorkbook.Sheets("Consol").Cells(y, 1)

Set consolRng = consolRng.Resize(rowsize:=UBound(scraped, 1), columnsize:=UBound(scraped, 2))
consolRng = scraped

wb.Close (Saved = True)

Next OFile

Loop

End Sub

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

根据MSDN documentationOpen方法的参数之一是password

Set wbk = Workbooks.Open(FileName:=yourfilename, Password:=yourPassword)