Error 1004 -Cannot open file . when I try to open workbooks in a folder

99封情书 提交于 2019-12-11 13:27:10

问题


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:


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.



来源:https://stackoverflow.com/questions/21123531/error-1004-cannot-open-file-when-i-try-to-open-workbooks-in-a-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!