'Our instance of Excel
Private ExcelProcess As Integer
'All other instances of Excel
Private ExcelProcesses() As Process
Private XLApp As Excel.Application = Nothing
Private Sub GetExcelProcessID(ByVal OurInstance As Boolean)
'This sub is run twice, first it collects all current instances of Excel (OurInstance = False)
'Then it identifies our instance (OurInstance = True)
'This way we have the Process ID for our instance
If Not OurInstance Then
ExcelProcesses = Diagnostics.Process.GetProcessesByName("Excel")
Else
Dim NewExcelProcesses() As Process = Diagnostics.Process.GetProcessesByName("Excel")
Dim found As Boolean
For Each p As Process In NewExcelProcesses
found = False
For Each p1 As Process In ExcelProcesses
If p.Id = p1.Id Then
found = True
Exit For
End If
Next
If Not found Then
ExcelProcess = p.Id
Exit For
End If
Next
End If
End Sub
Private Function StartExcel(ByVal Show As Boolean) As Boolean
ExcelProcess = Nothing
GetExcelProcessID(False)
Try
XLApp = New Excel.Application
XLApp.Visible = Show
GetExcelProcessID(True)
Return True
Catch ex As Exception
MessageBox.Show("Unable to start Excel because: " + ex.Message)
Return False
End Try
End Function
Private Function EndExcel() As Boolean
'Elsewhere all Excel objects have been properly closed
'Since following the "rules" has only limited success..
'..follow the rules ...
Try
Dim x As Integer = 0
XLApp.Quit()
x = System.Runtime.InteropServices.Marshal.FinalReleaseComObject(XLApp)
XLApp = Nothing
Return True
Catch ex As Exception
MessageBox.Show("Unable to exit Excel because: " + ex.Message)
Return False
Finally
'... now guarantee that our instance is killed
Diagnostics.Process.GetProcessById(ExcelProcess).Kill()
End Try
End Function