Home » excel » VBA/Excel: Search and filter variable folders within windows explorer, select a folder, and import its files

VBA/Excel: Search and filter variable folders within windows explorer, select a folder, and import its files

Posted by: admin May 14, 2020 Leave a comment


The goal is to be able to perform a directory search based on the selected cell in Excel and its “classification” cell below it, and return all folders in the directory whose names contain this selected information. From there, I want to be able to select a folder from that list and have its text files imported into the excel sheet next to the originally selected cell.

I’d ideally want this to work in a loop, where it’ll repeat this process four times and import the data from four different folders into new columns. All of this is for the sake of automating some data comparisons.

As I understand it, there’s no way to filter folder results in VBA’s Application.FileDialog(msoFileDialogFolderPicker) function, so I’ve been trying to figure out a workaround. Using some code from other posts on here, I’ve been able to get VBA to recreate the search function and pull it up in an explorer window, however, I don’t understand how to use this search string within a file import function.
Here’s my current code, which gets me to the filtered folder window I need:

Sub SearchExplorerForSelection()

Dim d As String
Dim searchpath As String
Dim searchlocation As String

Dim PartNumber As Range
Dim GenType As Range
' Cancel = True
d = Selection.Value

Set PartNumber = Selection 'Get desired part number from selected cell
Set GenType = PartNumber.Offset(2) 'Get PN's classification
PartNumberSearch = GenType & "*" & PartNumber 'Set full search keywords

searchpath = "search-ms:displayname=Search%20Results%20in%20" & GenType & "&crumb=filename%3A~" & PartNumberSearch
'copy string from manual search (e.g. my documents replace USERNAME)

searchlocation = "%20OR%20System.Generic.String%3A" & PartNumberSearch & "&crumb=location:Z%3A%5CTest%5CCalibration_Data_Generators%5C" & GenType
If Not d = "" Then
    Call Shell("explorer.exe """ & searchpath & searchlocation, 1)
   'src: https://stackoverflow.com/questions/24376850/open-explorer-search-from-excel-hyperlink

End If

End Sub

I’m very new to working with VBA.

How to&Answers:

EDIT – I think I might have mis-read your question as asking about searching file content, but it’s really about searching by folder name.

I think your best bet in that case would be to use Dir() or a FileSystemObject to loop over all folders under your “root” folder, and return a list of matching folder names to the user in a listbox – that could be on a worksheet or a userform. Then they can pick from that list.

Sub Tester2()

    Dim col As Collection, f

    Set col = GetFolderMatches("C:\Users\blahblah\Stuff", "Mail")

    For Each f In col
        Debug.Print f  '<< add to a list for the user to pick from
    Next f
End Sub

'Return a collection of folder paths given a starting folder and a term to search on
'  e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetFolderMatches(startFolder As String, nameIncludes As String, _
                    Optional subFolders As Boolean = True) As Collection

    Dim fso, fldr, f, subFldr
    Dim colFolders As New Collection
    Dim colSub As New Collection

    Set fso = CreateObject("scripting.filesystemobject")
    colSub.Add startFolder

    Do While colSub.Count > 0
        Set fldr = fso.getfolder(colSub(1))
        colSub.Remove 1
        If LCase(fldr.Name) Like "*" & LCase(nameIncludes) & "*" Then
            colFolders.Add fldr.Path
        End If
        If subFolders Then
            For Each subFldr In fldr.subFolders
                colSub.Add subFldr.Path
            Next subFldr
        End If
    Set GetFolderMatches = colFolders
End Function

Code below is not an answer to your question, but leaving it here because it’s interesting…

You can access Windows Search directly from VBA using ADO (add a reference to “Microsoft ActiveX Data Objects vx.x Library” in your VBA project)

Sub Tester()

    Dim conn As New ADODB.Connection, rs As ADODB.Recordset

    conn.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"

    Set rs = conn.Execute("SELECT System.ItemPathDisplay " & _
                          " FROM SYSTEMINDEX WHERE " & _
                          " SCOPE = 'C:\Users\blahblah\Desktop\Temp' " & _
                          " and contains('validated')")

    Do While Not rs.EOF
        Debug.Print rs(0).Value

End Sub

Based on: http://www.thejoyofcode.com/Using_Windows_Search_in_your_applications.aspx