僵尸 Excel 快把我逼疯了

Zombie Excel driving me insane

我有一个程序可以创建 excel 对象,写入 excel sheet,打印,另存为,最后退出。当然,我可以在任务管理器中看到一个 excel 僵尸程序,它只会在程序完全关闭后消失,(但在写入 excel 开始之前不会存在。)它正在驱动我疯了,我已经阅读了很多关于如何使用垃圾收集来解决这个问题的例子,但是 none 似乎有效。我也不想使用 kill process,因为这显然不是正确的方法。我也发誓我曾经让它工作过,也许当程序没有工作时,"save as" 一个新的 excel sheet。我相信错误可能是,我只关闭了一个 excel sheet 而新的另存为版本保持打开状态。 (使用 win 10 和 Excel 2016)

Dim objExcel As New Microsoft.Office.Interop.Excel.Application()
Dim objWorkbook As Excel.Workbook   'Represents a workbook object
Dim objWorksheet As Excel.Worksheet 'Represents a worksheet object
Dim OrderTemplate As String = "insert file path here"
objWorkbook = objExcel.Workbooks.Open(OrderTemplate)

objExcel.DisplayAlerts = False
objExcel.ActiveWorkbook.Close(SaveChanges:=True)
objExcel.DisplayAlerts = True
objExcel.Quit()
objExcel = Nothing


GC.GetTotalMemory(False)
GC.Collect()
GC.WaitForPendingFinalizers()

GC.Collect()
GC.WaitForPendingFinalizers()
GC.GetTotalMemory(False)


System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorksheet)   
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorkbook)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel)

Private Sub releaseObject(ByVal obj As Object)
    Try
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(obj)
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

您还需要定义 WorkBooks 集合,否则它将成为孤立的并且您将无法终止父应用程序:

Imports Excel = Microsoft.Office.Interop.Excel

Dim objExcel As New Excel.Application
Dim objWorkbooks As Excel.Workbooks = objExcel.Workbooks
Dim objWorkbook As Excel.Workbook = objWorkbooks.Open(OrderTemplate)
Dim objWorksheet As Excel.Worksheet = DirectCast(objWorkbook.Sheets(1), Excel.Worksheet)

然后按照以下顺序杀死对象:

    objWorksheet = Nothing
    objWorkbook.Close(False)
    objWorkbook = Nothing
    objWorkbooks = Nothing
    objExcel.Quit()
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel)
    objExcel = Nothing
    GC.Collect()

我读过的另一篇文章说也要对每个对象执行此操作(按此顺序):

System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorksheet)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorkbook)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objWorkbooks)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel)

我刚刚解决了这个问题... 没有理由要求 release()

只需将您的 excel 代码放在私人子目录中。 示例>

Private sub Excelexc()

'excel code

end sub

然后调用它。

Private Sub ButtonPreview_Click(sender As Object, e As EventArgs) Handles ButtonPreview.Click


    ExcelExc()


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


End Sub

还要确保以与打开对象相反的方式关闭 excel 对象。

            objExcel1.Visible = True
            objWorkbook1.Sheets.PrintPreview()
            objWorkbook1.Close(SaveChanges:=False)
            objExcel1.Quit()

这是我的。好吧,有很多方法可以修复它,但在某些情况下甚至很难摆脱双点之类的东西。 好吧,祝你好运。