closuresExcel.exe进程

下面的代码工作,但excel.exe进程仍然运行,即使我退出Excel。 我正在使用Office 2013并引用Office.Interop.Excel的正确导入

我错过了什么

 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 

如果你仍然有问题,你试图杀死这个过程?

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

不知道它是否会按照你想要的方式工作,但这是一个想法。

调用TryKillProcessByMainWindowHwnd(hWnd);GC.Collect()后执行该方法:

 [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; } 

你永远不应该调用Marshal.ReleaseComObject() – 更好的方法是通过调用GC.Collect()调用.NET垃圾收集器清理。

您必须小心,以确保与Excel交谈的代码与您的GC.Collect()方法不在同一个方法中,否则debugging器可能会使对象的存活时间超出您的预期。

一般的模式是:

 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