Excel VBA使用Shell打开应用程序,然后等待,直到它打开才能继续执行命令

基本上我想复制的Windows 7风格的剪切工具,所以当你打开它,它会得到一个剪辑准备。 但是在Windows 8中,它所做的只是打开程序,并且您必须按CTRL + N或单击新build。 我想避免使用睡眠(100)或其他时间function,因为它可能是不可靠的在不同的系统在一定的负载下。 我试过循环

While error <> 0 AppActivate "Snipping Tool", True application.SendKeys "^N", True exit sub Wend 

好。 这不是我用过的,但也是一样的。 问题是它不断给VBdebugging错误(除了这个例子,这是很好的和所有的),并毁了这个可能的解决scheme。 任何其他的想法等待shell能够运行之前打开程序

 Application.SendKeys "^N", True 

? 我也尝试过使用

 shell.Run FileLocation, 1 , True 

但是它会在closures后运行sendkeys! 这几乎是我想要的。


编辑:下面的工作代码

 //Used to wait for 200 milliseconds in the Sub. Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Public Function IsExeRunning(sExeName As String, Optional sComputer As String = ".") As Boolean On Error GoTo Error_Handler Dim objProcesses As Object Set objProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2").ExecQuery("SELECT * FROM Win32_Process WHERE Name = '" & sExeName & "'") If objProcesses.Count <> 0 Then IsExeRunning = True Error_Handler_Exit: On Error Resume Next Set objProcesses = Nothing Exit Function Error_Handler: MsgBox "The following error has occured." & vbCrLf & vbCrLf & _ "Error Number: IsExeRunning" & vbCrLf & _ "Error Description: " & Err.Description, _ vbCritical, "An Error has Occured!" Resume Error_Handler_Exit End Function Sub SnipTool() Dim wsh As Object Set wsh = VBA.CreateObject("WScript.Shell") wsh.Run "C:\Windows\sysnative\SnippingTool.exe" X = 0 Select Case Mid(Application.OperatingSystem, 21) Case 6.02 Do Until IsExeRunning("SnippingTool.exe") = True Or X = 200 //added Timeout if snipping tool fails to load. Prevents Excel freezing. X = X + 1 Loop Sleep (200) AppActivate "Snipping Tool", True Application.SendKeys "^N", True End Select End Sub 

您可以启动Exe然后从这里采取IsExeRunningfunction:

http://www.devhut.net/2014/10/20/vba-wmi-determine-if-a-process-is-running-or-not/

然后循环执行,直到IsExeRunning(SnippingToolExecutable)