recursion文件夹search组合CSV到主

我一直在使用这个 – 但它不是recursion的。 这怎么可以适应一个recursion的文件search合并大约100个.csv文件到一个工作簿?

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 

这是你可能想要的主要结构。 取决于您是要处理第一个文件夹(选项1)还是只处理子文件夹(选项2); select相应的选项来放置代码(replaceDebug.Print Path & Folder

主function:

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

recursion函数:

 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