错误1004 - 不打开文件。当我尝试在一个文件夹中打开工作簿
问题描述:
好的,我试图从文件夹中的几个工作簿中提取数据,并将它们全部放在一个文件中。当代码点击Workbooks.Open时,错误1004弹出,我确定文件没有损坏。
Alright I am trying to extract data from several workbooks in a folder and put them all in one file. When the code hits Workbooks.Open, error 1004 pops up and I am sure that the files are not corrupted.
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
答
p>
This works:
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
您需要在open命令中使用filepath,如 DIR
不返回路径,只返回文件名。
You need filepath in the open command, as DIR
does not return the path, only the filename.