Find files by extension
A common scripting task is to perform some task in a loop using data that resides in a collection of files on disk. The custom function, GetFiles, in the script example below shows how to retrieve a list of full file paths for all files with a given extension type in the specified directory.
In the script example, the concept is to search the folder specified by variable fDir for all files with extension "stp". After calling the GetFiles function, the array stpFiles() contains the full file path strings to each of the STP files found in the directory. The stpFiles() array is then looped over with a For loop and the full file path of each STP file is printed to the output window.
Sub Main
'Directory where the files reside
Dim fDir As String
fDir = "C:\temp\fred\support"
'Get the list of files in the directory
Dim stpFiles() As String, nFiles As Long
nFiles = GetFiles( fDir, "stp", stpFiles() )
'Report the list of files found
Dim curStpIdx As Long
Print ""
Print "STEP files found in directory:"
For curStpIdx = 0 To nFiles-1
Print Chr(9) & stpFiles(curStpIdx)
Next
Print ""
End Sub
Function GetFiles( ByVal in_dir As String, _
ByVal in_ext As String, _
ByRef out_FileList() As String ) As Long
'This helper function scans a directory for files
'with a specific extension returns their path names
'INPUTS:
' in_dir = string defining the directory to be searched
' in_ext = string defining the file extension
'OUTPUTS:
' returns the number of files that were found
' updates out_fileList to contain the full file paths
'Change to the search directory
ChDir( in_dir )
Dim nF As Long
Dim cFile As String
nF = 0
cFile = Dir$("*." & in_ext)
While cFile <> ""
If nF = 0 Then
ReDim out_FileList(0)
out_FileList(0) = in_dir & "\" & cFile
Else
ReDim Preserve out_FileList( nF )
out_FileList(UBound(out_FileList)) = in_dir & "\" & cFile
End If
nF += 1
cFile = Dir$()
Wend
Return nF
End Function