The next step is to define the GetFiles procedure which uses a module level array variable to hold the file names, dates and size and a module level long variable to contain the list count. These variables are required to hold the data needed to fill the list box displaying all the file names in the user selected foldler. To dimension the module level variables in the code behind the form, paste the following two lines at the top of the module but after any Option statements:
Private mlngI As Long
Private marDocNames As Variant
Then paste in the GetFiles procedure. This procedure calls the Dir function which returns the names of files at the path specified. If you call it in a loop, it will continue to find the next file in a folder until you exit the loop when an empty string is returned. In this case, the procedure may reside in the code behind the form (as there are references to the textbox containing the file path from the previous function) and also gets the size and date modified and sets the values in the module level array variable. This procedure could also be placed in a stand alone module as a function that receives the file path from a calling procedure in a form and returns the array to the caller. In this case, it assumes you have a listbox control on your form named 'lstFile'.
Private Sub GetFiles()
Dim strFileCrit As String
Dim strFileName As String
Dim strFilePath As String
Dim lngI As Long
If Len(Me.txtFilePath) Then
strFileCrit = "*.xls"
strFilePath = Me.txtFilePath & "\"
strFileName = Dir(strFilePath & strFileCrit, vbDirectory)
ReDim marDocNames(2, 0)
Do While Len(strFileName)
If Not (strFileName = ".." Or strFileName = ".") Then
ReDim Preserve marDocNames(2, lngI)
marDocNames(0, lngI) = strFileName
marDocNames(1, lngI) = FileDateTime(strFilePath & strFileName)
marDocNames(2, lngI) = FileLen(strFilePath & strFileName)
strFileName = Dir
lngI = lngI + 1
Else
strFileName = Dir
End If
Loop
mlngI = lngI
Me.lstFile = 0
Else
MsgBox "Please select a target path."
Exit Sub
End If
Me.lstFile.Requery
End Sub
Note the line:
strFileCrit = "*.xls"
You may instead use a textbox with a default value set in the property sheet as "*.xls" in order to permit users to substitute different file specifications. The "*.xls" tells the procedure to return only excel workbook files. If the specification was changed to "*.xlt", it would return only excel templates. "*.*" would return all file in the folder.
How to use the array to populate the list will be my next post.
Ciao
Jürgen Welz
Edmonton AB Canada
[email protected]