关闭Excel.exe进程

时间:2015-08-12 10:33:40

标签: vb.net excel

以下代码有效,但即使退出Excel,excel.exe进程仍会运行。我正在使用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

4 个答案:

答案 0 :(得分:0)

如果您仍然遇到问题,您是否试图杀死该进程?

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您永远不应该致电Marshal.ReleaseComObject() - 更好的方法是通过调用GC.Collect()来调用.NET垃圾收集器进行清理。

您必须小心确保与Excel通信的代码与GC.Collect()的方法不同,否则调试器可能会使对象的活动时间超出您的预期。

一般模式是:

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

答案 3 :(得分:0)

我有一个适用于excel文件2010的应用程序,我使用并关闭excel文件的唯一代码是dim workbook As Excel.Workbook => workbook.Close(),但我没有关闭excel应用程序或所有工作簿。试试吧。