Get List of Files within Sub-Directories using FSO (File System Object)

Get List of Files within Sub-Directories using FSO (File System Object)

FSO (File System Object)

Stands for File System Object which gives complete control over Drives, Folders and Files in Windows System. To understand complete File System Object using VBA please refer my previous article FSO (File System Object) using VBA. In this article we will do a PoC to find all files available within a Directory and underlying Sub Directories.

Code example

Public Sub ListAllFiles(oPath As String)
    'Declare file system object
    Dim FSO As FileSystemObject
    'Bind reference
    Set FSO = New FileSystemObject
    
    'Object to bind all parent files
    Dim oParentFiles As Files
    'Get all files of parent folder
    Set oParentFiles = FSO.GetFolder(oPath).Files
    
    'object to bind all sub folders
    Dim oSubFolders As Folders
    Set oSubFolders = FSO.GetFolder(oPath).SubFolders
    
    Dim oFile As File
    'Print files in parent or root folder
    For Each oFile In oParentFiles
    
        Debug.Print oFile.Name
    
    Next oFile
    
    'Iterate each sub folder
    Dim oFolder As Folder
    For Each oFolder In oSubFolders
        
        'object to bind all files in a sub folder
        Dim oListFiles As Files
        Set oListFiles = oFolder.Files
        
        'Print each file from sub folder
        For Each oFile In oListFiles
            
            'print file name
            Debug.Print oFile.Name
        
        Next oFile
        
        'cleanup
        Set oListFiles = Nothing
    Next oFolder
    
    'Memory cleanup
    Set oFolder = Nothing
    Set oFile = Nothing
    Set oSubFolders = Nothing
    Set oParentFiles = Nothing
    Set FSO = Nothing
End Sub

Calling method

Public Sub PrintAllFilesExample()
    Call ListAllFiles("C:\Users\Downloads\Bin")
End Sub

Please leave your comments or queries under comment section also please do subscribe to our blogs to keep your self upto date.

Leave a Reply

Your email address will not be published. Required fields are marked *