FileSystemObject列出所有子文件夹和文件

时间:2020-10-12 07:22:38

标签: vba fso

我正在将VBA与FileSystemObject一起使用。 我正在尝试列出目录中的所有子文件夹和文件,但是我没有在其中找到子文件夹和文件。

如何改进代码以拾取所有子子文件夹和文件(如果存在)以及根目录中没有任何子文件夹的文件?文件在层次结构的任何文件夹中可能存在或可能不存在。

enter image description here

Option Explicit
Sub GetFoldersSubFoldersFiles()

'Objects
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim fso As Object
    Dim fld As Object
    Dim sf As Object
    Dim f As Object
    
'Variables
    Dim i As Long
    Dim FolderName As String

'Excel environment - speed things up
    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
    End With
    
'Initilize variables
    i = 2
    FolderName = "C:\Data\"
    
'Instantiate objects
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("List")
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Right(FolderName, 1) <> "\" Then FolderName = FolderName + "\"
    Set fld = fso.getfolder(FolderName)
    
'List folder, subfolder, files
    If fso.folderExists(FolderName) Then
        For Each sf In fso.getfolder(FolderName).subfolders
            For Each f In sf.Files
                ws.Cells(i, 1).Value = FolderName
                ws.Cells(i, 2).Value = sf.Name
                ws.Cells(i, 3).Value = f.Name
                i = i + 1
            Next f
        Next sf
    End If
    
'Add Headers
    With ws
        .Cells(1, 1).Value = "Folder"
        .Cells(1, 2).Value = "SubFolder"
        .Cells(1, 3).Value = "File"
    End With

    
'Tidy up
'Destory objects
    Set ws = Nothing
    Set wb = Nothing

'Restore environment
    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
        .EnableEvents = True
        .Calculation = xlCalculationAutomatic
    End With

End Sub

谢谢

0 个答案:

没有答案