0

I the user to enter a keyword in a text box and when the macro is executed;

  • Open a new Windows' File Explorer window designated by a path.

    path = C:\Users\ME\Desktop\Folder7

  • Search from the variable in SearchBox1 (this is a ActiveX text box on a worksheet.)

    mySearch = sht.OLEObjects("SearchBox1").Object.Text & "*"

I saw multiple posts using Shell commands to open a File Explorer Window.

Call Shell("explorer.exe " & Chr(34) & "search-ms:query=*.pdf&crumb=location:C:\Users\ME\Desktop\Folder7" & Chr(34), vbNormalFocus)

When I run the above line there is an error from the explorer.

'Windows cannot find ". Make sure you typed the name correctly, and then try again.'

I need the macro to search for all files associated with the string. Folder names, file names, and words/characters within each type of document. They have all been OCR'd and Indexed by Windows.

It should have the ability to search for incomplete words as well.

I got Shell to open an explorer window to the path by

Call Shell("explorer.exe " & Chr(34) & "C:\Users\ME\Desktop\Folder7" & Chr(34), vbNormalFocus)

How can I search all folders and sub-folders within this freshly opened window?
I don't need the results compiled into Excel or any other program. I just need to make a quick search button as if you were to manually open this folder and use the search bar.

Community
  • 1
  • 1
Kenny
  • 343
  • 2
  • 9
  • 28
  • I may have gotten closer but now am stuck on my Variable within the string.. Call Shell("explorer.exe " & Chr(34) & "search-ms:displayname=Search%20Results%20in%20Folder7&crumb=System.Generic.String%3A(""mySearch"")&crumb=location:C%3A%5CUsers%5CME%5CDesktop%5CFolder7" & Chr(34), vbNormalFocus) – Kenny Oct 05 '18 at 19:32

4 Answers4

3

This worked for me:

Sub Tester()
    ShowSearch "C:\_Stuff\test", "*.pdf"           'search by file name
    ShowSearch "C:\_Stuff\Mail\", "reminder", True 'search by keyword
End Sub


Sub ShowSearch(searchWhere, searchFor, Optional SearchByKeyword As Boolean = False)
    Const CMD As String = "explorer.exe ""search-ms:crumb=name:{query}&crumb=location:{location}"" "
    Dim s
    s = Replace(CMD, "{query}", WorksheetFunction.EncodeURL(searchFor))
    s = Replace(s, "{location}", WorksheetFunction.EncodeURL(searchWhere))
    If SearchByKeyword Then s = Replace(s, "crumb=name:", "crumb=")
    'Debug.Print s
    Shell s
End Sub

Note: WorksheetFunction.EncodeURL() is 2013 and later. For alternatives see:

How can I URL encode a string in Excel VBA?

Tim Williams
  • 154,628
  • 8
  • 97
  • 125
1

Double Click on Cell to search

This is a solution I have combined from various places to open an explorer window at a path, that are filtered (searched) by the term in the selected cell using the windows File Explorer search function. It is triggered by a double click on a cell that contains the search term:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Application.Intersect(Target, Range("A1:AA1048576")) Is Nothing Then
Dim d As String
Dim searchpath As String
Dim searchlocation As String
Cancel = True
d = Selection.Value
'change window name to make sure new explorer window is opened for each instance
'copy string from manual search
searchpath = "search-ms:displayname=" & d & "%20Results%20&crumb=System.Generic.String%3A"
'copy string from manual search (e.g. my documents replace USERNAME)
searchlocation = "&crumb=location:C%3A%5CUsers%5CUSERNAME%5CDocuments"
If Not d = "" Then
    Call Shell("explorer.exe """ & searchpath & d & searchlocation & "", 1)
   'src: https://stackoverflow.com/questions/24376850/open-explorer-search-from-excel-hyperlink
End If
End If
End Sub

This opens the window in VbNormalFocus, with the window title set to the cell variable (d). The ensures that if this code is run on another cell value a new separate window will be opened. Without this I found the next time I ran the code the explorer window was not updated with the new search value, but just changed focus to the previous result.

edit: "copy from search bar" is the string after location: in the address bar of a manual search in explorer

Using ActiveX Controls

Add an ActiveX Text box (TextBox1) and button (CommandButton1) and add the following codeto the command button:

Private Sub CommandButton1_Click()
Dim d As String
Dim searchpath As String
Dim searchlocation As String
Cancel = True
d = TextBox1.Value
'change window name to make sure new explorer window is opened for each instance
'copy string from manual search
searchpath = "search-ms:displayname=" & d & "%20Results%20&crumb=System.Generic.String%3A"
'copy string from manual search (e.g. my documents replace USERNAME)
searchlocation = "&crumb=location:C%3A%5CUsers%5CUSERNAME%5CDocuments"
If Not d = "" Then
    Call Shell("explorer.exe """ & searchpath & d & searchlocation & "", 1)
   'src: https://stackoverflow.com/questions/24376850/open-explorer-search-from-excel-hyperlink
End If
End Sub

Now the user can change the text in the text box and clicking the button will open a windows file explorer search of the designated folder in the code.

Screenshot example using button search for "Editable Search Text"

EDIT

You can include additional search functions with the Windows search syntax: http://download.microsoft.com/download/8/1/7/8174a74e-3d8d-4478-abc6-84cd51ad93c4/Windows_Desktop_Advanced_Query_Reference.pdf

Eg. you can search within the folder for all files with a partial match of each word in the string by changing the search variable "d:

...
d = Selection.Value
d = "(" & Replace(d, " ", " OR ") & ")"
...

if the selection (d) had a value of Where will I find it This will search for (Where OR will OR I OR find OR it) in windows explorer and would return files with names such as WHEREver and Last WILL and testament. I've found this useful for qualitative information, where casting a wider search is acceptable and can be easily filtered through by the user (NOTE: the above example would also return all files with a name containing i so it is not very specific!)

TopCat13
  • 26
  • 3
  • thanks for responding. im a little confused. how do I have a activeX txt box or a txt field form control (does it matter which i use?), be the keyword for the search. i can't seam to figure out how to get your code to work. – Kenny Nov 12 '18 at 16:09
  • 1
    This code was just a snippet from a sheet I had which captured a double click on a cell containing the search value. I'll update my answer with more details and specifically more about having a text box and ActiveX controls... – TopCat13 Nov 13 '18 at 14:13
  • thanks for checking in. Yes, your explanation and pictures helped me understand. Much Appreciated – Kenny Dec 07 '18 at 10:53
0

executing Dir() empty after a Dir() with a given path will start to list all files in that dir, you just use if InStr() <> 0 to check against your value.

sFileName = Dir(path)
Do While sFileName > ""
tmp = tmp & sFileName & ";" : sFileName = Dir()
Loop
List() = Split(tmp, ";")

there you have a list of all files inside that path, you can check sub folders the same way by going through each one doing the same thing.

0

I do not take credit for the idea, it's awesome that you can do this. I just took the idea a step further and made it modular, so you can add any type of search:

Sub searchInExplorer_TEST()
    'searchInExplorer "D:\", , , True, "*.jpg", True, "24 Feb 20"
    searchInExplorer "D:\", , , , , True, "24 Feb 20", True, "picture"
End Sub


Sub searchInExplorer(searchWhere _
                    , Optional isSearchAll As Boolean, Optional strAll _
                    , Optional isSearchName As Boolean, Optional strName _
                    , Optional isSearchModified As Boolean, Optional strModified _
                    , Optional isSearchType As Boolean, Optional strType)
    
    '*****************************************************
    'https://stackoverflow.com/questions/52671500/vba-to-open-file-explorer-and-search-for-variable-in-textbox
    'ALLOWS SEARCHING IN WINDOWS EXPLORER USING VARIABLES
    'EITHER USE SEARCH ALL OR OTHER SEARCH TIMES
    'EACH SEARCH TYPE HAS AN ON/OFF SWITCH AND A STRING VARIABLE TO SEARCH BY
    '*****************************************************
        
    Dim STR As String
    
    STR = "explorer.exe ""search-ms:"
    If isSearchAll Then
        STR = STR & "crumb=:" & WorksheetFunction.EncodeURL(strAll)
        
    Else
        If isSearchName Then
            STR = STR & "&crumb=name:" & WorksheetFunction.EncodeURL(strName)
        End If
        
        If isSearchModified Then
            STR = STR & "&crumb=modified:" & WorksheetFunction.EncodeURL(strModified)
        End If
        
        If isSearchType Then
            STR = STR & "&crumb=kind:" & WorksheetFunction.EncodeURL(strType)
        End If
        
    End If
    
    STR = STR & "&crumb=location:" & WorksheetFunction.EncodeURL(searchWhere)
    STR = STR & """ "
    
    Debug.Print STR
    Shell STR
End Sub
Dumitru Daniel
  • 571
  • 4
  • 19