错误1004 – 无法打开文件。 当我尝试打开文件夹中的工作簿时

好吧,我正试图从一个文件夹中的几个工作簿中提取数据,并将它们全部放在一个文件中。 当代码命中Workbooks.Open,popup错误1004,我相信这些文件没有损坏。

Sub Extract_Class_Data() ' Extract_ERP_Class_Data Macro ' Goes into all the files in the folder and extracts the data from each of them. Dim MyFile As String Dim sourceBook As Workbook Dim sourceSheet As Worksheet Dim sourceSheetSum As Worksheet Set sourceBook = ActiveWorkbook Set sourceSheet = sourceBook.Sheets("Sheet1") Dim erow Dim Filepath As String Filepath = ThisWorkbook.Path MyFile = Dir(Filepath & "\*.xlsx") Do While Len(MyFile) > 0 If MyFile = "ZZZ.xlsm" Then Exit Sub End If **Workbooks.Open (MyFile)** Worksheets(Data).Activate Range("B6:B12").Select Selection.Copy ActiveWorkbook.Close savechanges:=False sourceSheet.Select ActiveSheet.Paste Range("B1").Select ActiveCell.Offset(0, 1).Select MyFile = Dir Loop End Sub 

这工作:

 Public Sub openaworkbook() Dim filen As String, filepath As String, myfile As String filen = "temp.xlsx" filepath = "c:\temp\" myfile = Dir(filepath & filen) Workbooks.Open (filepath & myfile) End Sub 

您需要打开命令中的文件path,因为DIR不会返回path,只有文件名。