I found a script and modified it to search for a filename in a folder and select the filename.
This code works fine when I use Shell "explorer.exe /select,""" & FilePath & """", vbNormalFocus
to open the folder and select the filename. However, it keeps opening a new folder instance instead of using the currently opened folder.
I tried to use this code:
If confirmfolder Then
Wnd.Visible = True
oShell.Open FolderPath & ""
ShellExecute 0, "Select", FilePath, vbNullString, vbNullString, vbNormalFocus
However, it does not select the filename in the folder at all. I’m not sure which part goes wrong, or maybe someone can help with this.
Below is my script.
Dim FolderPath As String
Dim PartialFilename As String
Dim FileFound As String
Dim FileSystem As Object
Dim Folder As Object
Dim File As Object
FolderPath = Worksheets("Automation").Range("H3").Value
PartialFilename = Format(Amount, "#,##0.00")
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Set Folder = FileSystem.GetFolder(FolderPath)
For Each File In Folder.Files
If InStr(1, File.Name, PartialFilename, vbTextCompare) > 0 Then
FileFound = FolderPath & "" & File.Name
Call SelectFileInExplorer(FileFound)
GoTo nextshow
End If
Next File
Set FileSystem = Nothing
Set Folder = Nothing
Option Explicit
#If VBA7 And Win64 Then
Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As LongPtr, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPtr
#Else
Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As LongPtr
#End If
Sub SelectFileInExplorer(FilePath As String)
Dim FolderPath As String
Dim confirmfolder As Boolean
Dim oShell As Object
Dim Wnd As Object
FolderPath = Left(FilePath, InStrRev(FilePath, "") - 1)
confirmfolder = False
Set oShell = CreateObject("Shell.Application")
For Each Wnd In oShell.Windows
If Wnd.Name = "File Explorer" Then
If Wnd.document.Folder.Self.Path = FolderPath Then
confirmfolder = True
Exit For
End If
End If
Next Wnd
If confirmfolder Then
Wnd.Visible = True
oShell.Open FolderPath & ""
ShellExecute 0, "Select", FilePath, vbNullString, vbNullString, vbNormalFocus
Else
Shell "explorer.exe /select,""" & FilePath & """", vbNormalFocus
End If
End Sub