2017-06-21 120 views
0

我需要創建一個合併目錄中的Excel文件列表的宏。 該文件夾包含我不想選擇的其他文件。所以,我需要指定文件列表(例如,選擇名稱中包含的所有文件「02.08 .xlsx」)。將excel文件列表合併到一個新的excel書中

這是我第一次使用VBA,所以請考慮這一點。 我試過一些東西,但我想我總是會遇到有關文件選擇的問題。

這是我到目前爲止已經試過,但沒有工作:

Sub MergeWorkbooks() 
Dim FolderPath As String 
Dim Filename As String 
Dim ListFilenames As Variant 
Dim Sheet As Worksheet 
Application.ScreenUpdating = False 
FolderPath = CurDir() 
ListFilenames = Array("*02.08.02.01*.xlsx", "*02.08.13.01*.xlsx") 
For i = 1 To 2 
    Filename = Dir(FolderPath & ListFilenames(i)) 
    Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True 
    For Each Sheet In ActiveWorkbook.Sheets 
    Sheet.Copy After:=ThisWorkbook.Sheets(1) 
    Next Sheet 
    Workbooks(Filename).Close 
    Filename = Dir() 
Next i 
Application.ScreenUpdating = True 
End Sub 
+0

看看這個Excel VBA代碼:https://www.extendoffice.com/documents/excel/2219-excel-list-all-folders-and-subfolders.html 有了這個,你可以列出所有文件或路徑上的文件夾,並與該數據,你可以過濾你希望 – danieltakeshi

+0

對於i = 1到2 是要更改對於i = 0到1 –

+0

@ Dy.Lee謝謝。仍然不起作用。我在定義文件名後放置了一張支票,但它總是空白。當我定義文件名時,有些事情是錯誤的。 – cinico

回答

1

的代碼是wouldb是這樣的。

Sub MergeWorkbooks() 
    Dim FolderPath As String 
    Dim Filename As String 
    Dim ListFilenames As Variant 
    Dim Sheet As Worksheet 
    Application.ScreenUpdating = False 
    FolderPath = CurDir() 
    ListFilenames = Array("*02.08.02.01*.xlsx", "*02.08.13.01*.xlsx") 
    For i = 0 To 1 
     Filename = Dir(FolderPath & "\" & ListFilenames(i)) 
     Do While Filename <> "" 
      Workbooks.Open Filename:=FolderPath & "\" & Filename, ReadOnly:=True 
      For Each Sheet In ActiveWorkbook.Sheets 
      Sheet.Copy After:=ThisWorkbook.Sheets(1) 
      Next Sheet 
      Workbooks(Filename).Close 
      Filename = Dir() 
     Loop 
    Next i 
    Application.ScreenUpdating = True 
End Sub 
+0

正如上面評論所述,問題是索引(應該從零開始)和缺少的文件路徑分隔符「\」。 – cinico

相關問題