Loop through files in a folder using VBA? Loop through files in a folder using VBA? vba vba

Loop through files in a folder using VBA?


Dir takes wild cards so you could make a big difference adding the filter for test up front and avoiding testing each file

Sub LoopThroughFiles()    Dim StrFile As String    StrFile = Dir("c:\testfolder\*test*")    Do While Len(StrFile) > 0        Debug.Print StrFile        StrFile = Dir    LoopEnd Sub


Dir seems to be very fast.

Sub LoopThroughFiles()    Dim MyObj As Object, MySource As Object, file As Variant   file = Dir("c:\testfolder\")   While (file <> "")      If InStr(file, "test") > 0 Then         MsgBox "found " & file         Exit Sub      End If     file = Dir  WendEnd Sub


Here's my interpretation as a Function Instead:

'#######################################################################'# LoopThroughFiles'# Function to Loop through files in current directory and return filenames'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba'#######################################################################Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String    Dim StrFile As String    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)    Do While Len(StrFile) > 0        Debug.Print StrFile        StrFile = Dir    LoopEnd Function


matomo