Chris Hanlon
Chris Hanlon

Reputation: 91

How can I kill task manager processes through VBA code?

I'm trying to kill certain processes through VBA. I have a proprietary object that connects to a market data bus. Through RTD I call this object to pub/sub to the bus. However sometimes the connection drops and I need to kill the process via task manager. Is there a way to kill a process through VBA?

Thanks

Upvotes: 7

Views: 71267

Answers (4)

Gianluca Colombo
Gianluca Colombo

Reputation: 819

Try with this code

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"   ' Display a message for testing purposes
      oProc.Terminate
    End If
Next

Upvotes: 26

Karuna Hebsur
Karuna Hebsur

Reputation: 1

Sub Kill_Excel()

Dim sKillExcel As String

sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide

End Sub

Upvotes: 0

user10769870
user10769870

Reputation: 11

You can perform it, this way:

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  'kill exe
    End If
Next

Upvotes: 1

omegastripes
omegastripes

Reputation: 12602

Take a look at one more example:

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

Upvotes: 9

Related Questions