Search code examples
excelvb.netmemory-managementwinforms-interop

Why won't the Excel process close while app is running


Question: Why won't the Excel process close while app is running? Please don't jump the gun and mark it duplicate. If you could show the change needed in the code I really appreciate it. Excel process closes nicely when I close the app. I researched this problem for last few day read several SO posts and tried several things but nothing is working except for calling process.kill which I prefer to avoid if possible.

Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices

Public Class Form1

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim misValue As Object
        Dim xlWorkSheet As Excel.Worksheet

        Try
            ''EXCEL CREATION/INITAILIAZATION
            misValue = System.Reflection.Missing.Value
            xlApp = New Microsoft.Office.Interop.Excel.Application()
            If xlApp Is Nothing Then
                MessageBox.Show("Excel is not properly installed!!")
                xlApp = Nothing
            End If
            xlWorkBook = xlApp.Workbooks.Add(misValue)


            ''WRITE TO WORKSHEET
            xlWorkSheet = TryCast(xlWorkBook.Sheets("sheet1"), Excel.Worksheet)
            xlWorkSheet.Cells(1, 1) = "THIS"
            xlWorkSheet.Cells(1, 2) = "IS"
            xlWorkSheet.Cells(1, 3) = "A"
            xlWorkSheet.Cells(1, 4) = "TEST"

            ''FORCEFULLY CAUSING ERROR, NOW THE EXCEL PROCESS HANGING IN TASK MANAGER 
            ''xlWorkSheet.Cells(1, -1) = "ERROR LINE"

            ''SAVE WORKSHEET
            Dim Name = DateTime.Now.ToString("s").Replace(":", "_")
            Dim Dir = AppDomain.CurrentDomain.BaseDirectory & "Output\" & Name & "Output.xls"
            xlApp.DisplayAlerts = False
            xlWorkBook.CheckCompatibility = False
            xlWorkBook.DoNotPromptForConvert = True
            xlWorkBook.SaveAs(Dir, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
                                Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
            xlWorkBook.Close(False)
            xlApp.Quit()

            misValue = Nothing

            If Not IsNothing(xlWorkSheet) And System.Runtime.InteropServices.Marshal.IsComObject(xlWorkSheet) Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
                xlWorkSheet = Nothing
            End If

            If Not IsNothing(xlWorkBook) And System.Runtime.InteropServices.Marshal.IsComObject(xlWorkBook) Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
                xlWorkBook = Nothing
            End If

            If Not IsNothing(xlApp) And System.Runtime.InteropServices.Marshal.IsComObject(xlApp) Then
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp)
                xlApp = Nothing
            End If

            GC.Collect()
            GC.WaitForPendingFinalizers()

        Catch ex As Exception
            Dim exMsg = ex.Message
        End Try
    End Sub

End Class

Solution

  • Your issue is double dot reference in .net. Read here :https://msdn.microsoft.com/en-us/library/8bwh56xe(v=vs.110).aspx

    so once you deconstruct

    xlWorkBook = xlApp.Workbooks.Add(misValue)
    

    as

    xlWorkBooks = xlApp.Workbooks
    xlWorkBook = xlWorkBooks.Add(misValue)
    

    and then release it, you are all good.

       Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Call doSomeWork()
        GC.Collect()
    End Sub
    
    Private Sub doSomeWork()
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkBooks As Excel.Workbooks '// Added new variable to avoid double dot.
        Dim misValue As Object
        Dim xlWorkSheet As Excel.Worksheet
    
        Try
            ''EXCEL CREATION/INITAILIAZATION
            misValue = System.Reflection.Missing.Value
            xlApp = New Microsoft.Office.Interop.Excel.Application()
            If xlApp Is Nothing Then
                MessageBox.Show("Excel is not properly installed!!")
                xlApp = Nothing
            End If
            xlWorkBooks = xlApp.Workbooks
            xlWorkBook = xlWorkBooks.Add(misValue)
    
    
            ''WRITE TO WORKSHEET
            xlWorkSheet = xlWorkBook.Sheets(1)
    
            'xlWorkSheet = TryCast(sheets("sheet1"), Excel.Worksheet)
            xlWorkSheet.Cells(1, 1) = "THIS"
            xlWorkSheet.Cells(1, 2) = "IS"
            xlWorkSheet.Cells(1, 3) = "A"
            xlWorkSheet.Cells(1, 4) = "TEST"
    
            ''FORCEFULLY CAUSING ERROR, NOW THE EXCEL PROCESS HANGING IN TASK MANAGER 
            ''xlWorkSheet.Cells(1, -1) = "ERROR LINE"
    
            ''SAVE WORKSHEET
            Dim Name = DateTime.Now.ToString("s").Replace(":", "_")
            Dim Dir = AppDomain.CurrentDomain.BaseDirectory & "Output\" & Name & "Output.xls"
            xlApp.DisplayAlerts = False
            xlWorkBook.CheckCompatibility = False
            xlWorkBook.DoNotPromptForConvert = True
            xlWorkBook.SaveAs("C:\temp\a.xls", Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
                                Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
            xlWorkBook.Close(False)
            xlApp.Quit()
    
            misValue = Nothing
    
        Catch ex As Exception
        End Try
    End Sub