我的班级中有这个子,只需打开excel即可查看范围是否存在。我遇到的问题是该过程不会关闭。我一直在谷歌搜索我的尾巴,我找不到解决方案。请看一下我的代码,看看我是否缺少一些简单的愚蠢。感谢。
Private Function NamedRangeExists(ByVal ProductFileName As String, ByVal RangeName As String) As Boolean
Dim ExcelApp As Excel.Application
'Create an Excel Object
ExcelApp = CType(CreateObject("Excel.Application"), Excel.Application)
Dim TheRange As Microsoft.Office.Interop.Excel.Name
Dim TheRangeName As String = ""
Dim ObjWorkbook As Excel.Workbooks = ExcelApp.Workbooks
'Open the Product
Dim TheProduct As Excel.Workbook = ObjWorkbook.Open(ProductFileName)
For Each TheRange In TheProduct.Names 'ExcelApp.ActiveWorkbook.Names
TheRangeName = CStr(TheRange.Name)
If (InStr(TheRangeName, RangeName) <> 0) Then
TheProduct.Save()
TheProduct.Close()
ExcelApp.Quit()
ExcelApp = Nothing
Marshal.ReleaseComObject(ExcelApp)
Return True
End If
Next
TheProduct.Close()
ObjWorkbook.Close()
ExcelApp.Quit()
Marshal.ReleaseComObject(ObjWorkbook)
Marshal.ReleaseComObject(TheProduct)
Marshal.ReleaseComObject(ExcelApp)
TheProduct = Nothing
ObjWorkbook = Nothing
ExcelApp = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
Return False
End Function
答案 0 :(得分:1)
对于任何未来的观众,这是我使用的一般方法:
Dim xlApp As New Excel.Application
Dim xlWB As Excel.Workbook = xlApp.Workbooks.Add
Dim xlWS As Excel.Worksheet = xlWB.Worksheets(1)
'do stuff
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
FinalReleaseComObject(xlWS)
xlWB.Close(False)
FinalReleaseComObject(xlWB)
xlApp.Quit()
FinalReleaseComObject(xlApp)
您需要Imports System.Runtime.InteropServices.Marshal
。
在垃圾收集之前,需要将任何其他声明的Excel对象(例如OP案例中的TheRange
)设置为Nothing
。
此处显示的命令序列非常重要。可以找到详细的解释here。
答案 1 :(得分:0)
这将完成这项工作! Documentation
Marshal.FinalReleaseComObject(obj)