简体   繁体   中英

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

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?

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

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

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

一个可能的解决方案是首先找出如何使用快捷键手动关闭,然后使用 vba 中的 sendkey 函数发送键以关闭

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM