2015-04-25 81 views
0

有人可以幫我解決以下問題: 我在「財政年度11-12」文件夾中有大約12個工作簿。所有12個文件都有一個名爲「Categorized」的通用表單。我試圖將數據從所有文件到文件YearlyExpense.xlsm的是紙張傳遞,但我得到了以下錯誤:將特定數據表中的多個文件傳輸到主文件

run-time error 1004. "xxx.xlsx" could not be found. Check the spelling of the name, and verify that the file location is correct.

我的代碼如下:

Sub LoopThroughDirectory() 

Dim MyFile As String 
Dim erow 
MyFile = Dir("C:\Users\Winston\Documents\Family Budget\Fiscal Year 11-12\") 

Do While Len(MyFile) > 0 
    If MyFile = "YearlyExpense.Xlsm" Then 
     Exit Sub 
    End If 

    Workbooks.Open (MyFile) 
     'This is where I'm getting error 1004 vba 

    Sheets("Categorized").Select 
    Range("B32:V32").Copy 
    ActiveWorkbook.Close 

    erow = Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 
    ActiveSheet.Paste Destination:=Worksheets("sheet2").Range(Cells(erow, 1), Cells(erow, 22)) 

    MyFile = Dir 
Loop 

末子

回答

0

您需要在首次調用Dir時表示目錄列表文件掩碼的完整路徑。這將只返回文件名;您需要將其與文件所在文件夾的路徑連接起來。處理第一個文件後,您需要再次撥打Dir以獲取該文件夾中符合原始文件掩碼的下一個文件。

Sub LoopThroughDirectory() 

    Dim myFile As String, myPath As String, wb As Workbook 

    myPath = "C:\Users\Winston\Documents\Family Budget\Fiscal Year 11-12\" 
    myFile = Dir(myPath & "\*.xl*") 

    Do While Len(myFile) > 0 
     If LCase(myFile) <> "yearlyexpense.xlsm" Then 

      Debug.Print myPath & Chr(92) & myFile 'use THIS to open the workbook 
      Set wb = Workbooks.Open(myPath & Chr(92) & myFile) 
      With wb.Sheets("Categorized") 
       'I'll admit to some confusion here as to what gets copied and to where 
       .Range("B32:V32").Copy _ 
        Destination:=ThisWorkbook.Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) 
      End With 
      wb.Close False 
      Set wb = Nothing 
     End If 
     myFile = Dir 
    Loop 

End Sub 
+0

您好,如前所述,我在指定的路徑中有12個excel文件。現在,目標是將每個文件中從B32:V32開始的行復制到下一個可用空行中的目標文件「yearlyexpense.xlsm」。 –

相關問題