我正在尝试打开某个文件夹中的所有工作簿。我的方法之一如下所示。奇怪的是,这(或者我尝试过的其他任何尝试)过去一直在起作用。它总是打开正确找到的第一个文件。第二个文件始终抛出错误1004。
我还尝试了Dir方法和CreateObject(“ WScript.Shell”)。Exec()来枚举文件(有效),然后在由此产生的变量数组上循环。所有这些都在第一个文件上起作用,而在第二个文件上崩溃。在将第二个文件提交给Workbooks.Open()之前,我已经检查了它的名称,它具有相同的路径(按预期),但是名称正确且不同。
Private Sub OpenWbsInPath(zPath As String)
Dim oFSO As Object, oFldr As Object, oFile As Object
zPath = IIf(Right$(zPath, 1) = "\", zPath, zPath & "\") ' Ensure trailing "\".
Set oFSO = CreateObject("Scripting.FileSystemObject") ' This is OK.
Set oFldr = oFSO.Getfolder(zPath) ' This OK.
For Each oFile In oFldr.Files
Workbooks.Open Filename:=oFile, UpdateLinks:=0 ' Error 1004 on 2nd file.
Next vFile
End Sub
处理错误并不能帮助我,因为我希望同时打开所有文件。我有足够的内存和相当快的机器。
Sub OpenWbsInPath(zPath As String)
Dim wb As Workbook
Dim zPath As String
Dim targetFile As String
Dim myExtension As String
If Right(zPath, 1) = "\" Then
'carry on as you need the \
Else
zPath = zPath & "\"
End If
'only get excel files
myExtension = "*.xlsx*"
'target workbook
targetFile = Dir(zPath & myExtension)
'Loop through each Excel file in folder
Do While targetFile <> ""
Set wb = Workbooks.Open(Filename:=zPath & targetFile) 'Set variable equal to opened workbook
DoEvents 'make sure workbook open before looping
targetFile = Dir 'get the next files name
Loop
End Sub