使用 Visual Studio .NET 客户端执行自动化功能后不退出 Office 应用程序 代码

1.

vb.net

Imports Microsoft.Office.Interop
Private Sub NAR(ByVal o As Object)
    Try
      System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
    Catch
    Finally
      o 
= Nothing
    End Try
  End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim oApp As New Excel.Application()
    Dim oBooks As Excel.Workbooks 
= oApp.Workbooks
    Dim oBook As Excel.Workbook 
= oBooks.Add
    Dim oSheet As Excel.Worksheet 
= oApp.ActiveSheet

    NAR(oSheet)
    oBook.Close(False)
    NAR(oBook)
    NAR(oBooks)
    oApp.Quit()
    NAR(oApp)

    GC.Collect()

    Debug.WriteLine(
"Sleeping")
    System.Threading.Thread.Sleep(
5000)
    Debug.WriteLine(
"End Excel")
End Sub

 

C#

Code

   exBook.Close(DBNull.Value, DBNull.Value, DBNull.Value)
            exApp.Workbooks.Close()
            exApp.Quit()
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exSheet)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook)
            exApp = Nothing
            exBook = Nothing
            exSheet = Nothing
            GC.Collect()

 参考文章:http://support.microsoft.com/?id=317109

posted @ 2008-09-10 21:44  ike_li  阅读(275)  评论(0编辑  收藏  举报