This code actually returns a correct result, but i can tell that it's flawed.
It loads a dictionary with all the files in a directory and all subdirectories.
It loads a dictionary with all the files in a directory and all subdirectories.
- I don't get a chance to `Set dFiles = Nothing`. Is there a way to check if it's the last loop?
- The initial caller uses `Set dF = Get_Files("C:\Data\Projects\Dev Tools\Updater")`, but the recursion uses `Get_Files oSubFolder.Path`. That's inconsistent. The reason is that the initial caller uses the return value, but the recursion uses the static object. Is there a way to make the recursion use the return value?
- Should the Dictionary object be passed as an argument?
- oFSO gets set to Nothing repeatedly during recursion, before i'm done using it, so it gets repeatedly recreated for sub-Directories. That doesn't make sense -- it shouldn't get destroyed until finished using it.
Code:
Function Get_Files(ByVal sDir As String) As Dictionary
Static dFiles As Dictionary
If dFiles Is Nothing Then Set dFiles = New Dictionary
Static oFSO As FileSystemObject
If oFSO Is Nothing Then Set oFSO = New FileSystemObject
Dim oFolder As IWshRuntimeLibrary.Folder
Set oFolder = oFSO.GetFolder(sDir)
Dim oFile As IWshRuntimeLibrary.File
For Each oFile In oFolder.Files
dFiles.Add oFile.Path, oFile.Name
Next oFile
Dim oSubFolder As IWshRuntimeLibrary.Folder
For Each oSubFolder In oFolder.SubFolders
Get_Files oSubFolder.Path 'recursion
Next oSubFolder
Set oFSO = Nothing
Set Get_Files = dFiles
End Function
Sub Test()
Dim dF As Dictionary
Set dF = Get_Files("C:\Data\")
Debug.Print dF.Keys(2)
End Sub
Last edited: