我有以下代碼(從在線教程中獲得)。該代碼正在工作,但我懷疑處理Excel COM對象的方式有點不合適。我們是否真的需要調用GC.Collect?或者什麼是處理這個Excel COM對象的最佳方式?使用VB.NET處理Excel com對象的正確方法?
Public Sub t1()
Dim oExcel As New Excel.Application
Dim oBook As Excel.Workbook = oExcel.Workbooks.Open(TextBox2.Text)
'select WorkSheet based on name
Dim oWS As Excel.Worksheet = CType(oBook.Sheets("Sheet1"), Excel.Worksheet)
Try
oExcel.Visible = False
'now showing the cell value
MessageBox.Show(oWS.Range(TextBox6.Text).Text)
oBook.Close()
oExcel.Quit()
releaseObject(oExcel)
releaseObject(oBook)
releaseObject(oWS)
Catch ex As Exception
MsgBox("Error: " & ex.ToString, MsgBoxStyle.Critical, "Error!")
End Try
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
[如何在C#中正確清理Excel互操作對象]可能的重複(http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c -sharp) – 2012-04-25 04:43:56
@Petr Abdulin,C#是我的一門外語。不完全重複。我甚至很難理解所謂的重複中接受的答案。 – 2012-04-25 05:19:51
你不應該*需要*調用'GC.Collect()' – Seph 2012-04-25 06:00:48