We help IT Professionals succeed at work.
Get Started

How to cleanly kill an Excel object from memory.

1,333 Views
Last Modified: 2012-05-09
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.

 
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

Open in new window

Comment
Watch Question
This problem has been solved!
Unlock 1 Answer and 12 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE