如何通过VBA代码终止任务管理器进程?

Chr*_*lon 4 excel vba process taskmanager

我试图通过VBA杀死某些进程.我有一个连接到市场数据总线的专有对象.通过RTD,我将此对象称为pub/sub到总线.但有时连接会丢失,我需要通过任务管理器终止进程.有没有办法通过VBA杀死进程?

谢谢

Gia*_*mbo 16

尝试使用此代码

Dim oServ As Object
Dim cProc As Variant
Dim oProc As Object

Set oServ = GetObject("winmgmts:")
Set cProc = oServ.ExecQuery("Select * from Win32_Process")

For Each oProc In cProc

    'Rename EXCEL.EXE in the line below with the process that you need to Terminate. 
    'NOTE: It is 'case sensitive

    If oProc.Name = "EXCEL.EXE" Then
      MsgBox "KILL"   ' used to display a message for testing pur
      oProc.Terminate()
    End If
Next
Run Code Online (Sandbox Code Playgroud)

  • 更简单一点,你可以使用:`set cProc = oServ.ExecQuery("Select*from Win32_Process Where Name ='EXCEL.EXE'")`只能获得Excel进程. (3认同)

ome*_*pes 9

再看一个例子:

Sub Test()
    If TaskKill("notepad.exe") = 0 Then MsgBox "Terminated" Else MsgBox "Failed"
End Sub

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