Private _excel As Excel.Application
Private _book As Excel.Workbook
Private _readOnly As Boolean = False
Private Sub openExcelFile(ByVal fileName As String)
' There is no error handling here: it has to be present in the
calling procedure
If _excel Is Nothing Then
_excel = New Excel.Application
_excel.Visible = False
End If
_book = _excel.Workbooks.Open(fileName:=fileName,
ReadOnly:=_readOnly, Notify:=False)
End Sub
Forgot to mention: the code in the previous code is part of a class that
deals with that specific workbook. It also contains the following code:
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
If Not _book Is Nothing Then
_book = Nothing
End If
If Not _excel Is Nothing Then
With _excel
' This particular instance of Excel was open for our work
only:
For Each wrk As Excel.Workbook In .Workbooks
wrk.Close(SaveChanges:=False)
Next
.Quit()
End With
_excel = Nothing
End If
When you create instances of your class, wrap them in Try..Catch..Finally
block and put code similar to the following into Finally:
If Not MyExcelClass Is Nothing Then
MyExcelClass.Dispose()
MyExcelClass = Nothing
End If
This is important, so that you do not have 'ghost' excel instances hanging
around after your application is closed.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.