How can I kill task manager processes through VBA code?
Asked Answered
M

4

7

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

Moshe answered 10/10, 2014 at 15:43 Comment(1)
Which processes? I did not downvote, but often these silent downvoters will do it because it's because you did not show your efforts so far(or explain why your google results are not helpful) to tackle the problem. It will help you and the next guy with the specific problem. Please Check this outWomanizer
M
23

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"   ' used to display a message for testing pur
      oProc.Terminate()
    End If
Next
Mcginley answered 10/10, 2014 at 15:52 Comment(3)
A little more straightforward, you can use: Set cProc = oServ.ExecQuery("Select * from Win32_Process Where Name = 'EXCEL.EXE'") to only get Excel processes.Insist
errReturnCode Variable Not definedOxazine
oProc.Terminate without bracketsExordium
N
9

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
Nilla answered 7/9, 2016 at 19:42 Comment(0)
T
1

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
Tronna answered 10/12, 2018 at 9:4 Comment(0)
E
0
Sub Kill_Excel()

Dim sKillExcel As String

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

End Sub
Elodiaelodie answered 7/2, 2019 at 9:0 Comment(1)
Please add some explanation to your code - to me, it looks like an answer that was already posted more than two years agoAmalea

© 2022 - 2024 — McMap. All rights reserved.