Closing the excel.exe process

The code is below, but the excel.exe process is still running, even if I exit Excel. I am using Office 2013 and reference the correct import for Office.Interop.Excel

I'm missing something

 Sub demo() Dim xls As New Excel.Application Dim book As Excel.Workbook Dim oSheet As Excel.Worksheet xls.Workbooks.Open("Test.xlsx") book = xls.ActiveWorkbook oSheet = book.ActiveSheet oSheet.Cells(1, 2).Value = "testing" book.Save() book.Close() xls.Workbooks.Close() xls.Quit() System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet) System.Runtime.InteropServices.Marshal.ReleaseComObject(book) System.Runtime.InteropServices.Marshal.ReleaseComObject(xls) oSheet = Nothing book = Nothing xls = Nothing GC.Collect() End Sub 
+4
source share
3 answers

If you still have problems with this, have you just tried to kill the process?

  Process[] procs = Process.GetProcessesByName("name"); foreach (Process proc in procs) proc.Kill(); 

Not sure if it will work the way you want, but this is an idea.

0
source

call TryKillProcessByMainWindowHwnd(hWnd); after GC.Collect() and method implementation:

 [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); public static bool TryKillProcessByMainWindowHwnd(int hWnd) { uint processID; GetWindowThreadProcessId((IntPtr)hWnd, out processID); if (processID == 0) return false; try { Process.GetProcessById((int)processID).Kill(); } catch (ArgumentException) { return false; } catch (Exception ex) { return false; } return true; } 
0
source

You should never call Marshal.ReleaseComObject() - the best approach is to call the .NET garbage collector to clean up by calling GC.Collect() .

You must be careful that the code that speaks to Excel is not the same as your GC.Collect() , otherwise the debugger might keep the objects alive longer than you expected.

The big picture:

 Sub WrapperThatCleansUp() ' NOTE: Don't call Excel objects in here... ' Debugger would keep alive until end, preventing GC cleanup ' Call a separate function that talks to Excel DoTheWork() ' Now Let the GC clean up (twice, to clean up cycles too) GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers() End Sub Sub DoTheWork() Dim xls As New Excel.Application Dim book As Excel.Workbook Dim oSheet As Excel.Worksheet xls.Workbooks.Open("Test.xlsx") book = xls.ActiveWorkbook oSheet = book.ActiveSheet oSheet.Cells(1, 2).Value = "testing" book.Save() book.Close() xls.Workbooks.Close() xls.Quit() ' NOTE: No calls the Marshal.ReleaseComObject() are ever needed End Sub 
0
source

All Articles