Other Wiki Sections

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.

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

Before calling the Application.Quit method, be sure to close any workbooks.

Be sure to release any variable references to Excel by setting the variables to Nothing (in VB) or null (in C#).

If after the above steps are taken, the problem still exists, you can follow the Application.Quit line with the code below. This will kill any Excel process that doesn't have a window title. Thus, it will leave any legitimate user instances open.

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