我试图让一个宏在完成后选择或激活Windows资源管理器窗口,如果找不到则打开窗口。目前它确实找到窗口句柄(保存为"窗口"),当它打开但它不会激活该窗口!
Private Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName As Any, ByVal lpWindowName As Any) 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
我还尝试了AppActivate directorySplit(UBound(directorySplit) - 1)
而不是FindWindow
,但它也会找到但不会激活窗口。我可以告诉它找到窗口及其句柄,因为如果我关闭浏览器窗口并尝试再次运行AppActivate
,则会引发错误。
任何帮助都将不胜感激。
答案 0 :(得分:2)
你能试试吗?
在这两种情况下,它对我有用。刚试了一次。
如果它在appactivate上出错,因为它找不到窗口,它会进入窗口打开部分并打开文件夹。
On Error GoTo WindowOpen
AppActivate directorySplit(UBound(directorySplit) - 1)
Exit Sub
WindowOpen:
Shell "explorer.exe " & directory, vbNormalFocus
答案 1 :(得分:1)
这是另一种解决方案 - 只需尝试关闭窗口(如果存在),然后从Shell调用同一窗口:
If Window <> 0 Then Windows(Window).Close
Shell "explorer.exe " & directory, vbNormalFocus
它应该非常强大,你可以通过VBA轻松改变焦点。