First how to search in a directory for a specific file extension :
Private Sub ListFiles(strPath As String, ByVal strExtension As String) 'Used for finding files and send them to a listbox named List1 Dim File As String 'Used to store the files that are found 'Simple check if the path is correct it hase to end with "\" else is added If Right$(strPath, 1) <> "\" Then strPath = strPath & "\" 'find the files with the extension in the current path File = Dir(strPath & strExtension) 'list all the file till dir return empty string Do While Len(File) List1.AddItem File 'add the file to the listbox File = Dir 'send the next file to variable File Loop End Sub
What this code does is first check if the path is correct: if there is no "\" at the end of the path, we add one. Then we pass the folder path and the extension to the Dir() function, which returns the files found matching that extension.
Here is how to find files matching multiple extensions:
Private Function search_filex(ParamArray vntSearch() As Variant) 'using the ParamArray we check for each of the elements for files Dim UB, LB As Long ' used for the Upper Bound(UB) and Low Bound(LB) of the array Dim i As Integer 'counter LB = LBound(vntSearch) 'Find the Upper Bound UB = UBound(vntSearch) 'Find Lower Bound For i = LB To UB 'list all elements of the array Call ListFiles("C:\Test_Dir\", CStr(vntSearch(i))) 'send the element to the function to find the file Next i End Function
Using Parameter Arrays we can send as many extensions as we want (the link contains the description of Parameter Arrays in VB6).
We send each element of the array to the function we just wrote to search for the files.
So here is the test button code:
Private Sub Command1_Click() 'test command button click event 'send 3 extensions to be listed search_filex "*.txt", "*.doc", "*.xml" End Sub
Here we send 3 extensions, "*.txt", "*.doc" and "*.xml"; the comma is used as the
separator for the elements of the Parameter Arrays.
Number of downloads: 1465
This post has been edited by NoBrain: 24 February 2010 - 08:19 AM