shell 获取vba excel在资源管理器上搜索的文件路径

mkshixfv  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(119)

我想得到在资源管理器上搜索的文件路径。
我用关键字在资源管理器上获得了搜索代码。
下面是我的代码:
“调用Shell(“explorer.exe“& Chr(34)&“search-ms:query=”& filename &“&crumb=location:“& filepath & Chr(34),vbNormalFocus)”
但是我无法得到搜索结果的路径。
每一个谁可以帮助我提供的代码,可以得到搜索结果的路径。
谢谢你的帮助

arknldoa

arknldoa1#

我不认为你可以得到从资源管理器返回的文件路径,而不使用一些花哨的windows代码。但是你可以用VBA模拟同样的事情。下面是一个工作代码示例。注意,它不像search=msquery那样查找部分匹配,但这是一个简单的调整。需要的话告诉我

Function SearchForFilesInFolderTree(filename As String, filepath As String, fSearchSubFolders As Boolean) As String
Dim fso As New Scripting.FileSystemObject
Dim fld As Scripting.Folder
Dim sfld As Scripting.Folder

If fso.FileExists(filepath & filename) = True Then
    SearchForFilesInFolderTree = filepath
    Exit Function
End If

If fSearchSubFolders = True Then
    Set fld = fso.GetFolder(filepath)
    For Each sfld In fld.SubFolders
        SearchForFilesInFolderTree = SearchForFilesInFolderTree(filename, sfld.Path & "\", True)
        If SearchForFilesInFolderTree <> "" Then Exit Function
        DoEvents
    Next sfld
Else
    SearchForFilesInFolderTree = ""
End If

字符串
结束函数
下面是一些关于如何调用上面代码的示例代码:

Sub TestSearch()
Dim filename As String
Dim filepath As String
Dim FoundFolder As String
Dim fSearchSubFolders As Boolean

fSearchSubFolders = True ' set to false if you only want to search the filepath folder and not subfolders
filename = "test.xlsx"  ' this is the file you want to search for.
filepath = "c:\temp"  ' This is the root folder of your search

If Right(Trim(filepath), 1) <> "\" Then filepath = Trim(filepath) & "\"

FoundFolder = SearchForFilesInFolderTree(filename, filepath, fSearchSubFolders)
If FoundFolder <> "" Then
    MsgBox "File " & filename & " found at: " & FoundFolder
Else
    MsgBox "File " & filename & " not found in: " & filepath
End If


结束子

相关问题