Reputation: 3259
I'm trying to get a macro to select or activate a windows explorer window after it has completed or open the window if it is not found. Currently it does find the window handle (saved as "window") when it is open but it will not activate that window!
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal hWnd As Long) As Long
Dim directory As String
directory = "C:\...\practice contracts\"
Dim directorySplit() As String
directorySplit = Split(directory, "\")
'--the rest of the macro--
Dim window As Long
window = FindWindow("CabinetWClass", directorySplit(UBound(directorySplit) - 1))
If window <> 0 Then
BringWindowToTop window
Else
Shell "explorer.exe " & directory, vbNormalFocus
End If
I've also tried AppActivate directorySplit(UBound(directorySplit) - 1)
instead of FindWindow
but it also will find but not activate the window. I can tell that it finds the window and its handle because if I close the explorer window and try running AppActivate
againt, it will raise an error instead.
Any help would be appreciated.
Upvotes: 4
Views: 4101
Reputation: 43585
This is another solution - simply try to close the window if it exists and then call the same window from the Shell:
If Window <> 0 Then Windows(Window).Close
Shell "explorer.exe " & directory, vbNormalFocus
It should work quite robustly and you can change the focus easily through VBA.
Upvotes: 1
Reputation: 7465
Can you please try this?
It worked for me in both conditions. Just tried it again.
If it errors out on appactivate because it cannot find the window, it goes to the window open section and opens the folder.
On Error GoTo WindowOpen
AppActivate directorySplit(UBound(directorySplit) - 1)
Exit Sub
WindowOpen:
Shell "explorer.exe " & directory, vbNormalFocus
Upvotes: 2