Question : How to cleanly kill an Excel object from memory.

We've all seen it.  That silly EXCEL.EXE stays resident in memory no matter what approach you take.  I've even seen multiple EXCEL.EXE objects appear in the process list in task manager when in fact my code only opens one occurence.  I came up with a way to kill all EXCEL's from memory.  I hope this helps your anguish in the matter.

 
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
Imports System
Imports System.Diagnostics

Private Sub printdocument1_EndPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles printdocument1.EndPrint

        Do While True
            'kill all resident excels in memory with extreme prejudice
            If CloseAllResidentExcels() = True Then
                Exit Do
            End If
        Loop
        
        'reinit your vars here
        xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
        wbkToShow = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
        wshToShow = DirectCast(wbkToShow.Worksheets("Sheet1"), Excel.Worksheet)

    End Sub
    Private Function CloseAllResidentExcels() As Boolean

        CloseAllResidentExcels = False

        Try
            'loop this process until there are no valid id's to return
            Dim Prc As Process
            Dim localByName As Process() = Process.GetProcessesByName("EXCEL")
            Prc = Process.GetProcessById(localByName(0).Id)
            Prc.Kill()

        Catch ex As Exception
            CloseAllResidentExcels = True
        End Try

    End Function
Related Solutions: excel staying in memory

Answer : How to cleanly kill an Excel object from memory.

ReleaseComObject and FinalReleaseComObject don't always work.  (If they ever do).  This is the only way I have been able to quite consistantly kill the ExcelApp in which I'm working.  This does NOT kill any other already-open Excel Files....only the one opened by your app at that time because you pass your ExcelApp object.

I use the "Application.DoEvents()" section just to give it a small amount of time to close.  You may not need it.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Int32, ByVal wMsg As Int32, _
    ByVal wParam As Int32, ByVal lParam As Int32) As Int32

Const WM_QUIT = &H12


Private Sub ExcelWorker

    MyExcel As Microsoft.Office.Interop.Excel.ApplicationClass
    
    'Blah Blah Blah Do all your Excel Stuffz

    MyExcel.Quit

    PostMessage(Excel.Hwnd, WM_QUIT, 0, 0)

    Dim i As Int32
    For i = 0 To 10000
        Application.DoEvents()
    Next

    MyExcel = Nothing

End Sub
Random Solutions  
 
programming4us programming4us