VBAmacros列出多个文件夹中的文件

我有下面的代码,我想获得水平列出的各种文件夹中的文件。 我怎样才能修改这段代码,以便列A中给定的文件path,我得到列C列中的文件? 我的知识只允许我做一个文件夹(而不是我想看的150)


`enter code here` Sub ListFiles() iCol = 3 Call ListMyFiles(Range("A5"), Range("B5")) End Sub Sub ListMyFiles(mySourcePath, IncludeSubfolders) Set MyObject = New Scripting.FileSystemObject Set mySource = MyObject.GetFolder(mySourcePath) On Error Resume Next For Each myFile In mySource.Files iRow = 5 Cells(iRow, iCol).Value = myFile.Name iCol = iCol + 1 Next If IncludeSubfolders Then For Each mySubFolder In mySource.SubFolders Call ListMyFiles(mySubFolder.Path, True) Next End If End Sub 

我在Excel 2007中testing了这个:

 Sub ListMyFiles(mySourcePath, IncludeSubfolders, iRow, iCol) Dim iColNow, iColSub Dim MyObject, mySource, myFile, mySubFolder Set MyObject = CreateObject("Scripting.FileSystemObject") Set mySource = MyObject.GetFolder(mySourcePath) On Error Resume Next iColNow = iCol For Each myFile In mySource.Files Cells(iRow, iColNow).Value = myFile.Name iColNow = iColNow + 1 Next If IncludeSubfolders Then ' 'iColSub = iCol + 1 ' iColSub = iCol For Each mySubFolder In mySource.SubFolders iRow = iRow + 1 Call ListMyFiles(mySubFolder.Path, IncludeSubfolders, iRow, iColSub) Next End If End Sub Sub ListFiles() Dim iRow, iCol iRow = 5 iCol = 3 Call ListMyFiles(Range("A5"), Range("B5"), iRow, iCol) End Sub 

IRow和iCol是控制结果输出起始位置的函数参数。 Range(“A5”)给出起始文件夹名称,如C:\ temp,Range(“B5”)是子文件夹列表控制键,1 = true,0 = false。

在这里输入图像说明 ========>

在这里输入图像说明

将为包含文件条目的文件夹创build一个空白行。

iRow是recursion修改的,为了改变每个子文件夹的行。

 'it's all in iRow `enter code here` Dim iRow as integer Sub ListFiles() iCol = 3 iRow = 5 Call ListMyFiles(Range("A5"), Range("B5")) End Sub Sub ListMyFiles(mySourcePath, IncludeSubfolders) Set MyObject = New Scripting.FileSystemObject Set mySource = MyObject.GetFolder(mySourcePath) On Error Resume Next For Each myFile In mySource.Files Cells(iRow, iCol).Value = myFile.Name iCol = iCol + 1 Next iRow = iRow + 1 If IncludeSubfolders Then For Each mySubFolder In mySource.SubFolders Call ListMyFiles(mySubFolder.Path, True) Next End If End Sub