I have a program that creates excel objects, writes to an excel sheet, prints, saves as, and finally quits. Of course however, there is an excel zombie I can see in the task manager that only goes away once the program is completely closed, (but is not there until the writing to excel begins.) It's driving me insane and I've read dozens of examples of how to use garbage collection to solve this issue however none seem to work. I'd prefer not to use kill process either, as that is clearly not the correct way to go about it. I also swear I had it working at one point, maybe when the program didn't, "save as" a new excel sheet. I believe the error could be, I am closing only one excel sheet while the new save as version is staying open. (Using win 10 and Excel 2016)
Dim objExcel As New Microsoft.Office.Interop.Excel.Application()
Dim objWorkbook As Excel.Workbook 'Represents a workbook object
Dim objWorksheet As Excel.Worksheet 'Represents a worksheet object
Dim OrderTemplate As String = "insert file path here"
objWorkbook = objExcel.Workbooks.Open(OrderTemplate)
objExcel.DisplayAlerts = False
objExcel.ActiveWorkbook.Close(SaveChanges:=True)
objExcel.DisplayAlerts = True
objExcel.Quit()
objExcel = Nothing
GC.GetTotalMemory(False)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.GetTotalMemory(False)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorksheet)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorkbook)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel)
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
I just tackled this earlier... there is no reason to call for release()
Just place your excel code in a private sub. example>
Private sub Excelexc()
'excel code
end sub
And then call it.
Private Sub ButtonPreview_Click(sender As Object, e As EventArgs) Handles ButtonPreview.Click
ExcelExc()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Also make sure you close the excel objects in the opposite way of opening them.
objExcel1.Visible = True
objWorkbook1.Sheets.PrintPreview()
objWorkbook1.Close(SaveChanges:=False)
objExcel1.Quit()
this is mine. Well, there are many ways to fix it, but in some cases its hard to even get rid of double dots and stuff like that. O well, good luck.