我打开了一些空白的excel实例。我希望能够关闭没有与之关联的工作簿的excel实例。
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
答案 0 :(得分:0)
要使Excel正常关闭,您必须卸载所有COM对象
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
如果您没有使用Excel实例并且只是显示它,那么可以试试这个。这将在创建过程后立即终止该过程,因此您希望将p.Kill()
放在另一个位置。另请注意,这会终止进程,因此不会保存任何更改。
Dim p As System.Diagnostics.Process = System.Diagnostics.Process.Start(path)
p.Kill()