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

时间:2014-01-14 20:39:13

标签: excel excel-vba vba

好吧我正在尝试从文件夹中的多个工作簿中提取数据并将它们全部放在一个文件中。当代码命中Workbooks.Open时,弹出错误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

1 个答案:

答案 0 :(得分:1)

这有效:

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不返回路径,只返回文件名。