Search code examples
excelvb.netoffice-interopclose-application

Excel still running after close vb.net app


I'm having some problems closing Excel files. I am doing a program that opens some Excel files, uses the information and then close them.
I tried some different codes, but they didn't work because the EXCEL process is still running.

My first code:

Dim aplicacaoexcel As New Excel.Application
Dim livroexcel As Object
Dim folhaexcel As Excel.Worksheet

livroexcel = aplicacaoexcel.Workbooks.Open("C:\Users\LPO1BRG\Desktop\Software Fiabilidade\Tecnicos.xlsx", UpdateLinks:=False, ReadOnly:=False, Password:="qmm7", WriteResPassword:="qmm7")
folhaexcel = livroexcel.sheets("Folha1")

aplicacaoexcel.DisplayAlerts = False
aplicacaoexcel.Visible = False
folhaexcel = Nothing
livroexcel.Close()
livroexcel = Nothing
aplicacaoexcel.Quit()
aplicacaoexcel = Nothing

Then I added this: System.GC.Collect() but it still not closing the Excel process.

Now I am trying this:

Dim process() As Process = system.Diagnostics.Process.GetProcessesByName("EXCEL")

For Each p As Process In process
   p.Kill()
Next

Actually, this one is working, but it closes all the Excel files (even those that are not opened by my program).

What can I do to close just the Excel files opened by my program? :)


Solution

  • Releasing the Excel.Application Interop COM object is a little bit trickier than other Office Interop objects, because some objects are created without your knowledge, and they all must be released before the main Application can be actually closed.

    These objects include:

    • The Excel.Application
    • The Excel.Application.WorkBooks collection
    • The WorkBooks collection opened WorkBook
    • The WorkBook Sheets collection
    • The Sheets collection referenced Worksheet

    These objects must all be released in order to terminate the EXCEL process.

    A simple solution is to use explicit declarations/assignment for all the COM objects:

    Dim ExcelApplication As New Microsoft.Office.Interop.Excel.Application()
    Dim ExcelWorkbooks As Workbooks = ExcelApplication.Workbooks
    Dim MyWorkbook As Workbook = ExcelWorkbooks.Open("[WorkBookPath]", False)
    Dim worksheets As Sheets = MyWorkbook.Worksheets
    Dim MyWorksheet As Worksheet = CType(worksheets("Sheet1"), Worksheet)
    

    When you're done, release them all:

    Imports System.Runtime.InteropServices
    
    Marshal.ReleaseComObject(MyWorksheet)
    Marshal.ReleaseComObject(worksheets)
    
    MyWorkbook.Close(False)   '<= False if you don't want to save it!
    Marshal.ReleaseComObject(MyWorkbook)
    
    ExcelWorkbooks.Close()
    Marshal.ReleaseComObject(ExcelWorkbooks)
    
    ExcelApplication.Quit()
    Marshal.FinalReleaseComObject(ExcelApplication)
    
    Marshal.CleanupUnusedObjectsInCurrentContext()