在 VBA 中使用 .Run 启动 .exe 时,典型的调用可能如下所示:
x = wsh.Run(Command:="program.exe ""argument""", WindowStyle:=0, waitonreturn:=False)
Run Code Online (Sandbox Code Playgroud)
理论上哪里windowStyle=0应该导致程序运行对用户不可见。但是,如果 .exe 中出现您不希望用户看到的弹出窗口,该怎么办?
windowStyle 输入不会抑制警告消息或弹出窗口的出现,声明诸如“计算完成”之类的内容向用户显示,这通常也会暂停代码,直到清除弹出窗口。以自动方式清除窗口(即单击“确定”)是微不足道的(请参阅此答案),但事实证明,作为一个相对初学者,阻止它一开始就出现在用户面前是很困难的。(即当弹出窗口由.exe触发时,它对用户来说是不可见的,然后由VBA代码自动关闭)
目前我使用此函数检测是否存在新的弹出窗口(其中 sCaption 是弹出窗口的名称):
Private Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim lhWndP As Long
Dim sStr As String
GetHandleFromPartialCaption = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
sStr = String(GetWindowTextLength(lhWndP) + 1, Chr$(0))
GetWindowText lhWndP, sStr, Len(sStr)
sStr = Left$(sStr, Len(sStr) - 1)
If InStr(1, sStr, sCaption) > …Run Code Online (Sandbox Code Playgroud)