0

I am opening an excel file from my winform using:

Dim xlsApp3 As Excel.Application
Dim xlsWB3 As Excel.Workbook
xlsApp3 = CreateObject("Excel.Application")
xlsApp3.Visible = True
xlsWB3 = xlsApp3.Workbooks.Open("C:\myfile.xlsm")

Try
    Marshal.ReleaseComObject(xlsWB3)
    Marshal.ReleaseComObject(xlsApp3)
    xlsWB3 = Nothing
    xlsApp3 = Nothing
Catch ex As Exception
    xlsWB3 = Nothing
    xlsApp3 = Nothing
Finally
    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
End Try

When I look at my task manager, it closes the process, but as soon as I close the excel application window that I open, the process comes back? If I close my whole winform application, thats when the excel process closes. Is the application holding on to the process in memory?

  • Possible duplicate of [Clean up Excel Interop Objects with IDisposable](https://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable) – TnTinMn Sep 27 '18 at 15:27

2 Answers2

1

Add the following lines:

xlsWB3.Close(True, Type.Missing, Type.Missing)        
xlsApp3.Quit
Dave
  • 142
  • 7
  • I can't close and quit it because I don't know when the user is done modifying the excel workbook that was opened. – ThisGuyJustNeedsHelp Sep 27 '18 at 14:03
  • Then why do you need interop at all? Just shellexecute the file: ShellExecute("C:\myfile.xlsm") – Dave Sep 27 '18 at 15:04
  • I need the workbook to open on it's own instance because i have other workbooks opened at the same time, and the way the workbook closes is closing the whole window thus it will close the other workbooks which i do not need it to do. – ThisGuyJustNeedsHelp Sep 27 '18 at 15:05
0

Don't access anything unmanaged with two dots like you did in

xlsApp3.Workbooks.Open

The Workbooks object is opened behind the scenes but .NET doesn't know about it and it can't clean it up properly.

Instead, you need to make a .NET reference to Workbooks, and the GC will clean everything up for you. Your entire code snippet can be reduced to this

Dim xlApp = New Excel.Application()
Dim xlBooks = xlApp.Workbooks
Dim xlBook = xlBooks.Open("C:\myfile.xlsm")
xlApp.Visible = True
djv
  • 15,168
  • 7
  • 48
  • 72