Array of files in a folder and all of its subfolders

Hello scripters,
I’m stuck here with a problem and I kope someone can point me in the right direction.
What I need is a list of all 3dm files within a folder and all of its subfolders.
The file list should be an array to use in a Listbox.
There are a number of examples to find online but they all print the file names one by one. That won’t do it for me. I need an array…

I tried this:

Dim aFiles(), i  'declared outside the subs

Sub Test1()
  
  i = 0
  Redim aFiles(0)
  Recurse("D:\Test")  
  
  Call Rhino.ListBox (aFiles)  
  
End Sub

Sub Recurse(sPath)
    Dim objFile, objSubFolder    
  Dim filesys   : set filesys = CreateObject("Scripting.FileSystemObject")
  Dim objFolder : set objFolder = filesys.GetFolder(sPath)
  
    For Each objFile In objFolder.Files
      If UCase(filesys.GetExtensionName(objFile.Name)) = "3DM" Then
        Redim Preserve aFiles(i)
        aFiles(i) = objfile.Name
        i = i + 1
      End If
    Next
  
    For Each objSubFolder In objFolder.SubFolders
        Recurse objSubFolder
    Next
  
End Sub  

Unfortunately it doesn’t work.
I wonder if its even possible to declare a dynamic array outside a sub and redim it in a sub.
If it’s not possible at all, how to get such an array?

Thanks in advance
Tobias

Hi @tobias,

How about this?

' TestTobias
Sub TestTobias
	Dim sFolder, aFiles(), oFSO, oFolder
	sFolder = "<add_path_here>"
	Set oFSO = CreateObject("Scripting.FileSystemObject") 
	Set oFolder = oFSO.GetFolder(sFolder)
	Call RecurseFolder(oFolder, aFiles)
	Call Rhino.Listbox(aFiles)
End Sub

' RecurseFolder
Sub RecurseFolder(ByRef oFolder, ByRef aFiles)
	Dim oFile, oSubFolder
	For Each oFile In oFolder.Files
		Call ArrayAdd(aFiles, oFile.Path)
	Next
	For Each oSubFolder In oFolder.SubFolders
		Call RecurseFolder(oSubFolder, aFiles)
	Next
End Sub 

' Adds a new element to the end of the array.
Sub ArrayAdd(ByRef arr, ByVal val)
	Dim ub
	If IsArray(arr) Then
		On Error Resume Next
		ub = UBound(arr)
		If Err.Number <> 0 Then ub = -1
		ReDim Preserve arr(ub + 1)
		arr(UBound(arr)) = val
	End If
End Sub

– Dale

Hi Dale,
Thanks a bunch for taking your time to come up with this example. The trick is the ByRef and ByVal. I know about the concept but I never use it. Now I see the need and how it works. Great!

Thanks again,
Tobias