Application.filesearch in Excel 2007 w/loop

拜拜、爱过 提交于 2019-12-01 11:59:57

This should get you pointed in the right direction:

Sub Your_Sub()

Dim FSO as Object
Dim FSO_FOLDER AS Object
Dim FSO_FILE as Object
Dim FILE_PATH as String
Dim FILE_EXT as String

FILE_PATH = "S:\My\File\Path"
FILE_EXT = "xls"

''Create FileSystem Objects
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO_FOLDER = FSO.GetFolder(FILE_PATH)

If FSO_FOLDER.Files.Count > 0 Then

    ''Loop through each File in Folder    
    For Each FSO_FILE IN FSO_FOLDER.Files

       ''Test extension
       If FSO.GetExtensionName(FSO_FILE.Name) = FILE_EXT Then
           ''Do your thing here
       Else:End if

    Next

Else

Msgbox "No Files Found at " & FILE_PATH

End If

Set FSO = Nothing
Set FSO_FOLDER = Nothing

End Sub
Yoan Tournade

For those that want to make old code that rely on Application.FileSearch work again with as little modification as possible, here a class that you can use as a replacement:

https://github.com/MonsieurV/VBA.Application.FileSearch

All you have to do is replacing your Set fs = Application.FileSearch by:

Dim fs As YtoFileSearch
Set fs = New YtoFileSearch

And use it as usual :

With fs
    .NewSearch
    .LookIn = "D:\User\Downloads\"
    .fileName = "*.pdf"
    If .Execute() > 0 Then
        Debug.Print "Found these PDF files:"
        For i = 1 To .FoundFiles.Count
           Debug.Print .FoundFiles(i)
       Next
    Else
        Debug.Print "Nothing found"
    End If
End With

If you don't have legacy code issues, better use directly Scripting.FileSystemObject or Dir() (see UberNubIsTrue answer)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!