2014-01-14 75 views
1

好吧我試圖從文件夾中的多個工作簿中提取數據,並將它們全部放入一個文件中。當代碼命中Workbooks.Open時,彈出錯誤1004,我確信這些文件沒有損壞。錯誤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 
+0

不是'DIR'返回文件名,但不是路徑?的 – Joe

+0

可能重複[運行時錯誤1004 - 未能找到工作簿(偶爾)(http://stackoverflow.com/questions/21120753/run-time-error-1004-failing-to-find-workbooks-occasionally) – pnuts

+0

相關。您可以查看['FileSystemObject'](http://msdn.microsoft.com/zh-cn/library/aa711216%28v=vs.71%29.aspx)以訪問磁盤上的文件。這比使用'dir'更直接 - – Brad

回答

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 

您需要的文件路徑在打開的命令,如DIR不返回的路徑,只有文件名。

相關問題