How to release Excel application objects
I have the following code below in which I have a class with some class level Excel objects defined. When I call excelModule.Test from another class all these Excel objects are getting created and I can se开发者_JS百科e an Excel instance in Task manager.
Do we have unload event for class to release these objects?
Module excelModule
Public myRange As Excel.Range
Public mySheet As Excel.Worksheet
Public wb As Excel.Workbook
Public ex As New Excel.Application
Public Sub Test()
End Sub
End Module
While Robert's suggestion of calling Quit may work, it's also flawed because if the user has Excel open before your application creates the Application object, then calling Quit will quit their open instance of Excel.
The issue is that the COM application doesn't know that you're done with the reference to the Excel Application object. Even if it goes out of scope and becomes eligible for garbage collection/finalization, the finalization won't occur immediately.
In some rare circumstances, it's necessary to call Marshal.FinalReleaseComObject on the COM object but most of the time this is not necessary.
So while explicitly triggering garbage collection is almost always frowned upon, the reality is that it is sometimes necessary in .NET/COM interop. Try this (after ensuring that you're no longer holding any references to Excel objects...)
GC.Collect();
GC.WaitForPendingFinalizers();
Because you are using unmanaged resources should change your module to a class and have that class implement the IDisposable interface. In the Dispose method make sure you dispose of the Excel object correctly.
Then when you use your excel wrapping class, do so in a Using
block:
Using e as New ExcelWrapper()
e.Test()
End Using
精彩评论