Error 1004 -Cannot open file . when I try to open

2019-08-06 19:42发布

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

1条回答
狗以群分
2楼-- · 2019-08-06 19:47

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

You need filepath in the open command, as DIR does not return the path, only the filename.

查看更多
登录 后发表回答