how to kill a app from task manager with VBA?

MikeYoungMoon
MikeYoungMoon used Ask the Experts™
on
I am looking for a way to to kill a running exe from task manager.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Microsoft Excel Expert
Top Expert 2014
Commented:
Lets say you want to Kill Notepad.

here it is

Sub TestKill()


Dim strTerminateThis As String
Dim objWMIcimv2 As Object, objProcess As Object, objList As Object
Dim intError As Integer


strTerminateThis = "Notepad.exe"


Set objWMIcimv2 = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set objList = objWMIcimv2.ExecQuery("select * from win32_process where name='" & strTerminateThis & "'")
For Each objProcess In objList
            intError = objProcess.Terminate

            If intError <> 0 Then Exit For
Next


Set objWMIcimv2 = Nothing
Set objList = Nothing
Set objProcess = Nothing

End Sub

Open in new window

NorieAnalyst Assistant
Commented:
How do you want to specify the exe to kill?

This will ask you to enter the name of the exe via an input box.
Sub KillEXE()
Dim oServ As Object
Dim oProc As Object
Dim cProc As Variant
Dim strEXEName As String
Dim Res As VbMsgBoxResult

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

    strEXEName = InputBox("Please enter name of process to kill:", "Kill process")
    
    For Each oProc In cProc
        
        If oProc.Name = "EXCEL.EXE" Then
        
            Res = MsgBox("Are you sure you want to kill this process?" & vbCrLf & vbCrLf & vbTab & vbTab & strEXEName, vbYesNo + vbQuestion, "Kill " & strEXEName)
            
            If Res = vbYes Then
                oProc.Terminate
            Else
                Exit Sub
            End If
            
        End If
        
    Next oProc
    
End Sub

Open in new window

Author

Commented:
Thank you both.

Both codes works.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial