Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function GetNextFile(FolderPath As String, FilePattern As String) As String
- Static FilePaths() As String
- Static CurrentIndex As Long
- Static Initialized As Boolean
- Dim FileName As String
- Dim SubFolder As String
- Dim FSO As Object
- Dim Folder As Object
- Dim SubFolders As Object
- Dim TempList As Collection
- Dim i As Long
- ' Initialize on the first call
- If Not Initialized Then
- ' Create a temporary list to store file paths
- Set TempList = New Collection
- Set FSO = CreateObject("Scripting.FileSystemObject")
- Set Folder = FSO.GetFolder(FolderPath)
- Set SubFolders = Folder.SubFolders
- ' Add files from the current folder
- FileName = Dir(FolderPath & "\" & FilePattern)
- Do While FileName <> ""
- TempList.Add FolderPath & "\" & FileName
- FileName = Dir
- Loop
- ' Add files from subfolders recursively
- For Each SubFolder In SubFolders
- AddFilesFromSubfolder SubFolder.Path, FilePattern, TempList
- Next SubFolder
- ' Transfer file paths from the collection to a static array
- ReDim FilePaths(1 To TempList.Count)
- For i = 1 To TempList.Count
- FilePaths(i) = TempList(i)
- Next i
- ' Initialize index and flag
- CurrentIndex = 1
- Initialized = True
- End If
- ' Return the next file path or an empty string if no more files
- If CurrentIndex <= UBound(FilePaths) Then
- GetNextFile = FilePaths(CurrentIndex)
- CurrentIndex = CurrentIndex + 1
- Else
- GetNextFile = "" ' No more files
- End If
- End Function
- Private Sub AddFilesFromSubfolder(FolderPath As String, FilePattern As String, TempList As Collection)
- Dim FileName As String
- Dim SubFolder As String
- Dim FSO As Object
- Dim SubFolders As Object
- ' Initialize FileSystemObject and get subfolders
- Set FSO = CreateObject("Scripting.FileSystemObject")
- Set SubFolders = FSO.GetFolder(FolderPath).SubFolders
- ' Add files from the current folder
- FileName = Dir(FolderPath & "\" & FilePattern)
- Do While FileName <> ""
- TempList.Add FolderPath & "\" & FileName
- FileName = Dir
- Loop
- ' Recursively add files from subfolders
- For Each SubFolder In SubFolders
- AddFilesFromSubfolder SubFolder.Path, FilePattern, TempList
- Next SubFolder
- End Sub
- Sub TestGetNextFile()
- Dim FolderPath As String
- Dim FilePattern As String
- Dim FilePath As String
- FolderPath = "C:\Your\Folder\Path" ' Replace with your folder path
- FilePattern = "*.ext" ' Replace with your file extension
- ' Retrieve files one at a time
- Do
- FilePath = GetNextFile(FolderPath, FilePattern)
- If FilePath = "" Then Exit Do
- Debug.Print FilePath ' Replace with your desired processing
- Loop
- End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement