关闭Excel.exe进程 [英] Closing Excel.exe process

查看:348
本文介绍了关闭Excel.exe进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below works, but the excel.exe process still runs even though I quit Excel. I am using Office 2013 and referencing the correct import for Office.Interop.Excel

我错过了一些



Am i 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


推荐答案

你不应该调用 Marshal.ReleaseCom Object() - 更好的方法是调用.NET垃圾收集器,通过调用 GC.Collect()来清理。

You should never call Marshal.ReleaseComObject() - the better approach is to call the .NET Garbage Collector to clean up by calling GC.Collect().

您必须小心确保与Excel交谈的代码与您的 GC.Collect()不一致。否则调试器可能会使对象的活动时间长于预期。

You have to be careful to ensure that the code talking to Excel is not in the same method as your GC.Collect(), else the debugger might keep objects alive longer than you'd expect.

一般模式将是:

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

这篇关于关闭Excel.exe进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆