列出子文件夹中的文件名

时间:2017-07-10 09:08:10

标签: excel vba excel-vba

我尝试在单独的文件夹中列出.txt文件中的文件名以在Excel中分隔列。(sample picture) 我找到了下面的代码,它运行良好,但不包含子文件夹或放置在具有文件夹标题的特定列中。

有人可以指出我在正确的方向吗?

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 

2 个答案:

答案 0 :(得分:1)

试试这个:

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

它将列出所选路径以及其中包含.txt的所有文件夹。但不是子子文件夹。 输出:

enter image description here

答案 1 :(得分:0)

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

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

enter image description here