Excel VBA - 停止运行由壳牌启动的程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1800066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:03:29  来源:igfitidea点击:

Excel VBA - Stop running program that was started by Shell?

excelexcel-vbavba

提问by John M

Excel 2002 VBA.

Excel 2002 VBA。

I have a macro that launches an external script whenever a certain condition is met:

我有一个宏,可以在满足特定条件时启动外部脚本:

Shell("c:\program\script.exe")

How do I stop that running program when the condition is not met?

当条件不满足时,如何停止正在运行的程序?

回答by Igor Zevaka

Since Shell returns the process ID of the process you started you could try using pskill with that procedd ID to stop it:

由于 Shell 会返回您启动的进程的进程 ID,您可以尝试使用 pskill 和该 procedd ID 来停止它:

dim pid
pid = Shell("c:\program\script.exe")
'...Do something
Shell "pskill " & pid

Shell reference: https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/shell-function

外壳参考:https: //docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/shell-function

回答by Martin H.

This will also close the application:

这也将关闭应用程序:

TaskKill = CreateObject("WScript.Shell").Run("taskkill /f /im " & "script.exe", 0, True)

And it can be transformed to a re-usable function as follows:

并且可以将其转换为可重用的功能,如下所示:

Function TaskKill(sTaskName)
   TaskKill = CreateObject("WScript.Shell").Run("taskkill /f /im " & sTaskName, 0, True)
End Function