在子文件夹中列出文件名

我试图从单独的文件夹中的.txt文件列出文件名到Excel中的单独列( 示例图片 )。我发现下面的代码,这很好,但不包括子文件夹或文件夹标题的特定列中的位置。

有人可以在这里指出我的方向吗?

Option Explicit Sub GetFileNames() Dim xRow As Long Dim xDirect$, xFname$, InitialFoldr$ InitialFoldr$ = "C:\main folder dir\" With Application.FileDialog(msoFileDialogFolderPicker) .InitialFileName = Application.DefaultFilePath & "\" .Title = "Please select a folder to list Files from" .InitialFileName = InitialFoldr$ .Show If .SelectedItems.Count <> 0 Then xDirect$ = .SelectedItems(1) & "\" xFname$ = Dir(xDirect$, 7) Do While xFname$ <> "" ActiveCell.Offset(xRow) = xFname$ xRow = xRow + 1 xFname$ = Dir Loop End If End With End Sub 

所以:

 Subfoldername1 | Subfoldername2 -------------- | -------------- Textfile1 | Textfile3 Textfile2 | Textfile4 

尝试这个:

 Sub FolderNames() Dim sht As Worksheet Dim fso As Object, fl1 As Object, fl2 As Object Dim lCol As Long Dim Files As String, sPath As String Set fso = CreateObject("Scripting.FileSystemObject") Set sht = Worksheets("Sheet1") With Application.FileDialog(msoFileDialogFolderPicker) .AllowMultiSelect = False .Title = "Please Select a Folder" .Show If .SelectedItems.Count <> 0 Then sPath = .SelectedItems(1) End With Set fl1 = fso.GetFolder(sPath) With sht lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column If .Cells(1, lCol).Value = "" Then .Cells(1, lCol) = sPath Else .Cells(1, lCol + 1) = sPath End If End With For Each fl2 In fl1.SubFolders lCol = sht.Cells(1, sht.Columns.Count).End(xlToLeft).Column sht.Cells(1, lCol + 1).Value = Right(fl2, Len(fl2) - InStrRev(fl2, "\")) Files = Dir(fl2 & "\*.txt") Do While Files <> "" With sht lrow = .Cells(.Rows.Count, lCol + 1).End(xlUp).Row .Cells(lrow + 1, lCol + 1).Value = Files End With Files = Dir() Loop Next sht.Columns.AutoFit End Sub 

它会列出所选的path和所有包含.txt的文件夹。 但不是子子文件夹。 输出:

在这里输入图像说明

请参阅下面的链接。 我认为这会做你想做的事,或者至less,它会让你非常接近你需要的地方。

http://learnexcelmacro.com/wp/2011/11/how-to-get-list-of-all-files-in-a-folder-and-sub-folders/

在这里输入图像说明