我之前通过从EXCEL发布工作表,工作簿和应用程序对象解决了浮动EXCEL.EXE文件。但是,我注意到在引用单元格范围之后,此.EXE文件将返回。
我已经注释了我引用这些单元格的部分,这实际上是正在发生的事情。我试过释放细胞本身和细胞的范围,但这不起作用。
我知道这可能是一个重复的问题,但这是我真正理解的问题。
Dim app As New Microsoft.Office.Interop.Excel.Application
Dim book As Microsoft.Office.Interop.Excel.Workbook = app.Workbooks.Open(file)
Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = book.Worksheets("Sheet1")
app.Visible = True
While (worksheet.Cells.Range("A" & max_row).Value IsNot Nothing)
max_row = max_row + 1
End While
If max_row > 2 Or max_row = 2 Then
For i As Integer = 2 To max_row Step 1
MessageBox.Show("here")
Dim add As DataRow = Me.CentralDatabaseDataSet.Selected_Equipment.NewRow
If "Section " & worksheet.Cells.Range("J" & i).Text = cboSection.SelectedItem.ToString Then
add("Type") = worksheet.Cells.Range("A" & i).Text
ReleaseObject(worksheet.Cells(i, 1))
'add("Description") = worksheet.Cells.Range("B" & i).Text
'add("Model Number") = worksheet.Cells.Range("C" & i).Text
'add("Serial Number") = worksheet.Cells.Range("D" & i).Text
'add("Asset Number") = worksheet.Cells.Range("E" & i).Text
'add("Manufacturer ID") = worksheet.Cells.Range("F" & i).Text
'add("Department ID") = worksheet.Cells.Range("G" & i).Text
'add("Last Calibration") = worksheet.Cells.Range("H" & i).Text
'add("Calibration Due Date") = worksheet.Cells.Range("I" & i).Text
'Me.CentralDatabaseDataSet.Selected_Equipment.AddSelected_EquipmentRow(add)
End If
Next
End If
book.Close()
app.Quit()
ReleaseObject(worksheet)
ReleaseObject(book)
ReleaseObject(app)
答案 0 :(得分:0)
您永远不必致电Marshal.ReleaseComObject()
- 更好的方法是通过调用GC.Collect()
来调用.NET垃圾收集器进行清理。
您必须小心确保与Excel通信的代码与GC.Collect()
的方法不同,否则调试器可能会使对象保持活动的时间超出您的预期。
一般模式是:
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 app As New Microsoft.Office.Interop.Excel.Application
Dim book As Microsoft.Office.Interop.Excel.Workbook = app.Workbooks.Add()
Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = book.Worksheets("Sheet1")
app.Visible = True
For i As Integer = 1 To 10
worksheet.Cells.Range("A" & i).Value = "Hello"
Next
book.Save()
book.Close()
app.Quit()
' NOTE: No calls the Marshal.ReleaseComObject() are ever needed
End Sub