Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Killing Stray Excel References - Excel Automation

RSS
Modified on Mon, May 11, 2009, 2:59 PM by Administrator Categorized as Microsoft Office
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.

  • 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

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.