Monday, January 4, 2016

How to Find File in Folder and Subfolders in VBA

To find files in a folder and its subfolder.

1
2
3
Sub Sample()
    Call FileSearch("D:\ExcelPaidjo")
End Sub


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Sub FileSearch(Path As String)
    Dim FSO As Object, Folder As Variant
    Set FSO = CreateObject("Scripting.FileSystemObject")
    For Each Folder In FSO.GetFolder(Path).SubFolders
        Debug.Print Folder.Path
        Call FileSearch(Folder.Path)
    Next Folder
    For Each File In FSO.GetFolder(Path).Files
        Debug.Print File.Path
    Next File
End Sub

To find all excel type files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Sub FileSearch(Path As String)
    Dim FSO As Object, Folder As Variant
    Set FSO = CreateObject("Scripting.FileSystemObject")
    For Each Folder In FSO.GetFolder(Path).SubFolders
        Debug.Print Folder.Path
        Call FileSearch(Folder.Path)
    Next Folder
    For Each File In FSO.GetFolder(Path).Files
        If InStr(File.Type, "Excel") > 0 Then
            Debug.Print File.Path
        End If
    Next File
End Sub



Download File









No comments :

Post a Comment