簡體   English   中英

無法從VB.NET應用程序關閉Excel進程

[英]Unable to close Excel process from VB.NET app

我創建了下面的類來打開並收集excel文件中工作表的名稱。 它在打開文件並返回每個單獨工作表的名稱時應該這樣做。 不幸的是,我無法關閉文件。 這使Excel.exe進程保持掛起狀態。 即使我試圖在這個類的底部關閉它,這個過程仍然會掛起。 在我再次使用該文件之前,我必須手動轉到Windows任務管理器並終止該過程。 即使我退出應用程序,它仍然在那里。 關於如何從代碼中刪除此進程的任何建議?

Imports Excel = Microsoft.Office.Interop.Excel

Public Class ExcelWrapper

Dim strTypeSelection As String = String.Empty
Dim strFilePath As String = String.Empty

Function GetWorksheetsByName(ByVal strfilePath As String) As Array

    Dim xlsApp As Excel.Application
    Dim xlsWorkBook As Excel.Workbook

    xlsApp = New Excel.Application
    xlsWorkBook = xlsApp.Workbooks.Open(strfilePath)
    Dim intWsCount As Integer = xlsApp.Worksheets.Count

    Dim sarWorksheetName(intWsCount - 1) As String

    Dim i As Integer = 0
    'gathers the names off all the worksheets 
    For Each totalWorkSheets In xlsApp.Worksheets
        sarWorksheetName(i) = totalWorkSheets.Name
        i += 1
    Next totalWorkSheets

    xlsWorkBook.Close(strfilePath)
    xlsApp.DisplayAlerts = False
    xlsApp.Quit()

    Return sarWorksheetName
End Function

End Class

我之前也遇到過這個問題,並且我記得解決方案是在來自Office庫的所有對象上調用Marshal.ReleaseComObject(Object obj)Marshal.FinalReleaseComObject(Object obj) 我很容易就錯了。 祝你好運,辦公自動化是一個巨大的痛苦。

對於每個參考嘗試添加;

System.Runtime.InteropServices.Marshal.ReleaseComObject(xxx)
xxx = nothing

http://support.microsoft.com/kb/317109

來自http://www.experts-exchange.com/Programming/Misc/Q_24049269.html

' after creating it, but before operating on it
xlsApp.Application.DisplayAlerts = False

這是我通過自動化使用Excel時使用的清理代碼。 您必須正確清理,否則過程會因您看到而掛起。 我假設您通過桌面應用程序而不是Web應用程序執行此操作。 這通常在finally塊中完成,樣本是c#,但我認為您應該能夠根據您的需要進行調整。

 GC.Collect();
 GC.WaitForPendingFinalizers();


 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(range);
 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet);
 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(book);

 WB.Close(false, Type.Missing, Type.Missing);

 Excel.Quit();
 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Excel);

這不是特定於您的Excel問題; 但是您可以使用名稱來殺死進程...

Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("WhateverYouWant")

For Each p As Process In pProcess
    p.Kill()
Next

這將終止與特定名稱匹配的所有進程。

您可能想嘗試添加Excel = Nothing以查看是否可以解決問題(並且您可以避免強行終止該進程'。

我會像這樣修改代碼的結尾部分,以糾正可能導致問題的一些問題:

For Each totalWorkSheets as Excel.Worksheet In xlsWorkBook.Worksheets 'not xlsApp.Worksheets
   sarWorksheetName(i) = totalWorkSheets.Name
   i += 1
Next totalWorkSheets

xlsWorkBook.Close Savechanges:=False 
set xlsWorkBook = Nothing
xlsApp.Quit()
set xlsApp = Nothing

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM