2017-09-11 9 views
0

私はこれを使用していますが、再帰的ではありません。どのようにこれを再帰的なファイル検索に適合させて約100の.csvファイルを1つのブックにマージすることができますか?CSV to Masterを結合するための再帰的フォルダ検索

Sub test() 
    Dim myDir As String, fn As String, wb As Workbook 
    Set wb = ActiveWorkbook 
    With Application.FileDialog(msoFileDialogFolderPicker) 
     If .Show Then myDir = .SelectedItems(1) & "\" 
    End With 
    If myDir = "" Then Exit Sub 
    fn = Dir(myDir & "*.csv") 
    Do While fn <> "" 
     With Workbooks.Open(myDir & fn) 
      .Sheets(1).Copy after:=wb.Sheets(wb.Sheets.Count) 
      .Close False 
     End With 
     fn = Dir 
    Loop 
End Sub 
+0

[サブフォルダを巡回上のこの古い答えはあなたを助けるかもしれない](HTTPS ://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user-specified-root-directory) – Pslice

答えて

1

これは、おそらく必要な主な構造です。最初のフォルダ(オプション1)またはサブフォルダ(オプション2)のみを処理するかどうかによって異なります。 (Debug.Print Path & Folderを交換する)あなたのコードを配置するため、それぞれのオプションを選択します

主な機能:

Sub MainListFolders() 
    ListFolders ("C:\Temp\") 
End Sub 

再帰関数:

Sub ListFolders(Path As String) 
Dim Folder As String 
Dim FolderList() As String 
Dim i As Long, Count As Long 
    Folder = Dir(Path, vbDirectory) 
    ' Option 1: Can process folder here 
    'Debug.Print Path & sFolder 
    Do While Folder <> vbNullString 
     ' Check that it is a Folder 
     If CBool(GetAttr(Path & Folder) And vbDirectory) Then 
      ' We don't want to include the Current (".") or Previous ("..") folders, so.. 
      If Replace(Folder, ".", vbNullString) <> vbNullString Then 
       ' Option 2: Can process folder here 
       Debug.Print Path & Folder 
       ' Store the list of Sub-Folders to recursively check at the end 
       ' If you try to do a recursive call here, when it jumps back, it wont be able to process the next Dir() 
       ' because the Dir() folder would have changed in the recurive call. 
       ReDim Preserve FolderList(Count) 
       FolderList(Count) = Folder 
       Count = Count + 1 
      End If 
     End If 
     Folder = Dir() 
    Loop 
    ' Do the recursive calls here 
    For i = 0 To Count - 1 
     ' Make sure to add the "\" to the end 
     ListFolders Path & FolderList(i) & "\" 
    Next 
End Sub 
関連する問題