Help Man Help Man - 6 months ago 17
Vb.net Question

close instance of excel that does not have workbook associated with?

I have some blank instance of excel opened. I want to be able to close the instances of excel that does not have a workbook associated with it.

Public xlsApp As Excel.Application
Public xlsWB As Excel.Workbook

public openExcel()
Try
Dim path As String
path = "C:\excel.xlsm"
xlsWB = xlsApp.Workbooks.Open(path)
Catch ex As Exception
My.Application.Log.WriteException(ex, TraceEventType.Error, "Additional information or details")
Exit Sub
End Try
end sub

Public Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

====when run will open one excel, if excel window is close, the instance stays on, you will see the blank excel workbook. I want to close that instance when this sub re runs.
public doThis()
releaseObject(xlsApp)
releaseObject(xlsWB)
openExcel() <<==
end sub

Answer

For Excel to close properly you have to unload all of your COM objects

        Dim xl As Excel.Application = New Excel.Application()
        Dim wb As Excel.Workbook = xl.Workbooks.Add()
        Dim ws As Excel.Worksheet = wb.Worksheets.Add()


        wb.Close()
        xl.Quit()
        ReleaseComObject(ws)
        ReleaseComObject(wb)
        ReleaseComObject(xl)
        ws = Nothing
        wb = Nothing
        xl = Nothing

If you aren't consuming the Excel instance and you are just displaying it then maybe try this. This will kill the process as soon as it is created so you'll want to put the p.Kill() in another place. Also note that this kills the process so no changes will be saved.

Dim p As System.Diagnostics.Process = System.Diagnostics.Process.Start(path)
p.Kill()