Fill Listbox With Found Files

Jaye7

Well-known Member
Joined
Jul 7, 2010
Messages
1,069
I found the following script to open found files, however can someone please adapt the script so that rather than open the files it actually lists the file name in listbox1 of userform1 and lists the file path in listbox2.

Thanks

Code:
With Application.FileSearch
  .NewSearch
  .LookIn = "I:\IsolationDataBase\IsolationProcedures"
    .SearchSubFolders = True
    .Filename = Range("A1").Value
    .MatchTextExactly = True
    .FileType = msoFileTypeAllFiles
    If .Execute() > 0 Then
      For j = 1 To .FoundFiles.Count
        Workbooks.Open Filename:=.FoundFiles(j)
      Next j
    Else
      MsgBox "file Not found"
    End If
 
End With
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
Please note that the .FileSearch is deprecated in Excel 2007 and later. (Deprecated = No longer supported).

For Excel 2003 and earlier, the code you presented should search the "I:\IsolationDataBase\IsolationProcedures" folder and all folders below it open all files that match the value in A1

.MatchTextExactly deals with text that is contained in the files, which you have not defined.

If multiple files match the value in A1 having the filenames in one listbox and the filepaths in another list box may prove awkward.

This code does as you asked:
Code:
Option Explicit
Global aryFoundFiles As Variant
Sub PopulateListBoxWithFiles()
    Dim aryFilenames() As Variant
    Dim strFileName As String
    Dim strPath As String
    Dim booSame As Boolean
    Dim intX As Integer
    Dim intY As Integer
    Dim strFileDirectory As String
    Dim strSort1 As String
    Dim strSort2 As String
 
    strFileDirectory = "I:\IsolationDataBase\IsolationProcedures"
    strFileName = Range("A1").Value
 
    'Select Directory  - "Uncomment section below to allow a directory to be chosen at runtime
'    With Application.FileDialog(msoFileDialogFolderPicker)
'        .Title = "Select the directory"
'        .AllowMultiSelect = False
'        .ButtonName = "Select"
'        .InitialFileName = ThisWorkbook.Path
'        .Show
'        If .SelectedItems.Count > 0 Then
'            strFileDirectory = .SelectedItems.Item(1)
'        End If
'    End With
 
    UserForm1.ListBox1.Clear
 
    ReturnFilePathNameArray strFileDirectory, strFileName
 
    If Len(aryFoundFiles(1)) = 0 Then
        MsgBox "No files met criteria."
    Else
        aryFilenames = aryFoundFiles
 
        'Sort array
        For intX = 1 To UBound(aryFilenames)
           For intY = intX To UBound(aryFilenames)
                If UCase(aryFilenames(intY)) < UCase(aryFilenames(intX)) Then
                    strSort1 = aryFilenames(intX)
                    strSort2 = aryFilenames(intY)
                    aryFilenames(intX) = strSort2
                    aryFilenames(intY) = strSort1
                End If
            Next intY
        Next intX
 
        booSame = True
        strPath = Left(aryFilenames(1), InStrRev(aryFilenames(1), "\"))
        For intX = 2 To UBound(aryFilenames)
            If strPath <> Left(aryFilenames(intX), InStrRev(aryFilenames(intX), "\")) Then
                booSame = False
                Exit For
            End If
        Next
 
        If booSame Then 'All files returned are in the same directory
            UserForm1.ListBox2.List = Array(strPath) 'Display common path in listbox2
            'Remove path from aryFilenames
            For intX = 1 To UBound(aryFilenames)
                aryFilenames(intX) = Mid(aryFilenames(intX), InStrRev(aryFilenames(intX), "\") + 1, 100)
            Next
        Else
            UserForm1.ListBox2.List = Array("Multiple Directories Returned")
        End If
 
        UserForm1.ListBox1.List = aryFilenames()
        UserForm1.Show (vbModeless)
 
    End If
End_Sub:
 
End Sub
Sub ReturnFilePathNameArray(strPath As String, strFileLike As String)
    'Dim strPath As String
    Dim fso As FileSystemObject 'Add reference to Microsoft Scripting Runtime
    'Dim strFileLike As String
 
    ReDim aryFoundFiles(1 To 1)
    'strPath = "C:\PAB\Burn (Old)"
    'strFileLike = "*o*.*"
    'strFileLike = Range("A1")
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFiles fso, strPath, strFileLike
 
    ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1)
 
    Set fso = Nothing
 
End Sub
 
Sub GetFiles(fso As FileSystemObject, strPath As String, strFilePattern As String)
    Dim fldr As Folder
    Dim fldrSub As Folder
    Dim oFile As Object
    'Dim aryFoundFiles As Variant
 
    Set fldr = fso.GetFolder(strPath)
 
    If fldr.Files.Count > 0 Then
        For Each oFile In fldr.Files
            If oFile.Name Like strFilePattern Then
                aryFoundFiles(UBound(aryFoundFiles)) = oFile.Path
                ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) + 1)
            End If
        Next
    End If
    If fldr.SubFolders.Count > 0 Then
        For Each fldrSub In fldr.SubFolders
            GetFiles fso, fldrSub.Path, strFilePattern
        Next
    End If
 
    Set fldr = Nothing
End Sub

I do not think this is the most efficient code available, comments are welcomed.
 
Upvote 0
Hi Phil.

The code is bugging out at the following, I am using excel 2000 version.

Code:
Sub GetFiles(fso As FileSystemObject, strPath As String, strFilePattern As String
 
Upvote 0
You have to add a reference to Microsoft Scripting Runtime
In the VBA editor select Tools | References
Scroll down to Microsoft Scripting Runtime
Put a check next to it
Click OK

(I had that as a comment, but it got cut while cleaning up the code.)

I am not sure if the code will work with Excel 2000 - I don't have that version to check it on. Code should work with XL 2003 and later, but can't be sure about other versions.
 
Upvote 0
I have added the reference, now it is bugging out on the following line.

Code:
ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1)

which is within the following script

Code:
Sub ReturnFilePathNameArray(strPath As String, strFileLike As String)
    'Dim strPath As String
    Dim fso As FileSystemObject 'Add reference to Microsoft Scripting Runtime
    'Dim strFileLike As String
 
    ReDim aryFoundFiles(1 To 1)
    'strPath = "C:\PAB\Burn (Old)"
    'strFileLike = "*o*.*"
    'strFileLike = Range("A1")
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFiles fso, strPath, strFileLike
 
    ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1)
 
    Set fso = Nothing
 
End Sub
 
Upvote 0
What is the error message? Is the Global statement in the same module?

Global aryFoundFiles As Variant
 
Upvote 0
The whole script that you provided is in the same module.

error message is

runtime error 9

subscript out of range
 
Upvote 0
Run it again till it stops then Debug and as see what value UBound(aryFoundFiles) evaluates to. It should be the number of files in and under the I:\IsolationDataBase\IsolationProcedures" directory

If that value is greater than 1, Comment out:
ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1)

and try again - perhaos XL 2000 did not like a truncation of the array.

Signing off for tonight.
 
Upvote 0
If UBound(aryFoundFiles) is 1 at the ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1) line, there are no files being returned. I added some error checking. Check that the hardcoded path being searched is correct and try again.

Code:
Option Explicit
 
Global aryFoundFiles As Variant
 
Sub PopulateListBoxWithFiles()
    'Searches I:\IsolationDataBase\IsolationProcedures for filename.ext pattern (wildcards OK) in cell A1
    'If no pattern in A1 then *.* is used to return all files.
 
    'Add reference to Microsoft Scripting Runtime (VBA editor: Tools | References)
 
    'Calls ReturnFilePathNameArray
 
    Dim aryFilenames() As Variant
    Dim strFileName As String
    Dim strPath As String
    Dim booSame As Boolean
    Dim intX As Integer
    Dim intY As Integer
    Dim strFileDirectory As String
    Dim strSort1 As String
    Dim strSort2 As String
 
    strFileDirectory = "I:\IsolationDataBase\IsolationProcedures"
    strFileName = Range("A1").Value
 
    'Select Directory  - "Uncomment section below to allow a directory to be chosen at runtime
'    With Application.FileDialog(msoFileDialogFolderPicker)
'        .Title = "Select the directory"
'        .AllowMultiSelect = False
'        .ButtonName = "Select"
'        .InitialFileName = ThisWorkbook.Path
'        .Show
'        If .SelectedItems.Count > 0 Then
'            strFileDirectory = .SelectedItems.Item(1)
'        End If
'    End With
    'Verify the A1 value is the desired filename
    strFileName = InputBox("Enter the filename or pattern (wildcards OK) to search for", "Search for", "*.*")
 
    'Next code line checks for existance of filename and defaults to *.* if it is not present
    'more checks should be added to ensure only valid filenames are used.
    If strFileName = "" Then strFileName = "*.*"
 
    UserForm1.ListBox1.Clear
 
    ReturnFilePathNameArray strFileDirectory, strFileName
 
    If Len(aryFoundFiles(1)) = 0 Then
        'Do nothing - error msgbox was displayed by 'ReturnFilePathNameArray' procedure
    Else
        aryFilenames = aryFoundFiles
 
        'Sort array
        For intX = 1 To UBound(aryFilenames)
           For intY = intX To UBound(aryFilenames)
                If UCase(aryFilenames(intY)) < UCase(aryFilenames(intX)) Then
                    strSort1 = aryFilenames(intX)
                    strSort2 = aryFilenames(intY)
                    aryFilenames(intX) = strSort2
                    aryFilenames(intY) = strSort1
                End If
            Next intY
        Next intX
 
        booSame = True
        strPath = Left(aryFilenames(1), InStrRev(aryFilenames(1), "\"))
        For intX = 2 To UBound(aryFilenames)
            If strPath <> Left(aryFilenames(intX), InStrRev(aryFilenames(intX), "\")) Then
                booSame = False
                Exit For
            End If
        Next
 
        If booSame Then 'All files returned are in the same directory
            UserForm1.ListBox2.List = Array(strPath) 'Display common path in listbox2
            'Remove path from aryFilenames
            For intX = 1 To UBound(aryFilenames)
                aryFilenames(intX) = Mid(aryFilenames(intX), InStrRev(aryFilenames(intX), "\") + 1, 100)
            Next
        Else
            UserForm1.ListBox2.List = Array("Multiple Directories Returned (" & UBound(aryFilenames) & ") files.")
        End If
 
        UserForm1.ListBox1.List = aryFilenames()
        UserForm1.Show (vbModeless)
 
    End If
End_Sub:
 
End Sub
 
Sub ReturnFilePathNameArray(strPath As String, strFileLike As String)
    'Calls GetFiles
 
    Dim fso As FileSystemObject 'Add reference to Microsoft Scripting Runtime
    ReDim aryFoundFiles(1 To 1)
 
    Set fso = CreateObject("Scripting.FileSystemObject")
    GetFiles fso, strPath, strFileLike
 
    If UBound(aryFoundFiles) = 1 Then
        MsgBox "No files were returned for this starting directory: " & strPath & vbLf & _
            "and this file pattern: " & strFileLike
    Else
        ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) - 1)
    End If
 
    Set fso = Nothing
 
End Sub
 
Sub GetFiles(fso As FileSystemObject, strPath As String, strFilePattern As String)
    Dim fldr As Folder
    Dim fldrSub As Folder
    Dim oFile As Object
 
    Set fldr = fso.GetFolder(strPath)
 
    If fldr.Files.Count > 0 Then
        For Each oFile In fldr.Files
            If UCase(oFile.Name) Like UCase(strFilePattern) Then 'UCase makes search case insensitive
                aryFoundFiles(UBound(aryFoundFiles)) = oFile.Path
                ReDim Preserve aryFoundFiles(1 To UBound(aryFoundFiles) + 1)
            End If
        Next
    End If
    If fldr.SubFolders.Count > 0 Then
        For Each fldrSub In fldr.SubFolders
            GetFiles fso, fldrSub.Path, strFilePattern
        Next
    End If
 
    Set fldr = Nothing
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,557
Messages
6,179,508
Members
452,918
Latest member
Davion615

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top