Killing Stray Excel References - Excel Automation

When coding against the Excel object model (i.e., using Excel Automation), at times, the Quit() of the Excel.Application object appears not to work properly, as an extra instance of Excel is visible in the Windows Task Manager.

Image

Here's a few strategies for closing the stray instance of Excel.


Dim excelProcesses() As Process = Process.GetProcessesByName("Excel")

For Each p As Process In excelProcesses
    If p.MainWindowTitle.Length = 0 Then
        p.Kill()
    End If
Next

Code for a more precise way to kill the Excel instance follows. This code will kill ONLY the instance of Excel you created, but it will momentarily show the Excel window, so it's not the most professional looking solution.

''-- Kill Stray EXCEL.EXE Process -----------------------------------------------------
' This uniquely identifies this instance of Excel so we can kill the process later
guid = System.Guid.NewGuid().ToString().ToUpper()
app.Visible = True ' Excel MUST be visible in order for this technique to work!
app.Caption = guid

            
' Don't bother trying the Quit method, since it typically fails when called from .NET
'app.Quit()
'System.Runtime.InteropServices.Marshal.ReleaseComObject(app)
'app = Nothing

Dim excelProcesses() As Process = Process.GetProcessesByName("Excel")

For Each p As Process In excelProcesses
    If p.MainWindowTitle.Contains(guid) Then
        p.Kill()
    End If
Next