0

I have a DataGridView that can open Excel files. Once I close the Excel file, the instance is still open in the Windows Task Manager processes. If I open up another Excel file from the DataGridView, another instance opens again and so forth. Is there any way to close the instance when the Excel file is closed? If I close the form that my DataGridView is in, all Excel instances are closed.

Here's my code:

Public Sub openExcel()
    'my code.... blah blah blah....

    'open excel
    Dim xlsApp As Excel.Application
    Dim xlsWB As Excel.Workbook
    xlsApp = New Excel.Application
    xlsApp.Visible = True
    xlsWB = xlsApp.Workbooks.Open(c:\myExcelFile.xlsm")
End Sub
Blackwood
  • 4,504
  • 16
  • 32
  • 41

1 Answers1

0

Change

 xlsWB = xlsApp.Workbooks.Open(c:\myExcelFile.xlsm")

to

 Dim workbooks as Excel.Workbooks = xlsApp.Workbooks
 xlsWB = workbooks.Open(c:\myExcelFile.xlsm")

Then for every single variable created, be sure to call

 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks)
 System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWB)

etc, etc, lots and lots of etc.

These are all COM objects and until they are released they stay alive in memory.

xlsApp.Workbooks.Open creates a reference to a Workbooks object with no variable, so there's no way to explicitly release it.

Every object created in the Excel object model needs its own variable, and each one must be explicitly released, even if an exception is thrown.

That may lead you to the conclusion (as it did for me) that it's just not worth the hassle, and you're better off using a library like EPPlus. Or try reading from it like it's a database.

One reason why I recommend looking at alternatives is that this is likely not the only issue you will encounter. Of all the ways to read an Excel spreadsheet, starting an instance of Excel and automating it is the most problematic. I've heard of cases where the application prompts for some input, except it's a) invisible and b) on a web server where no one could see the prompt anyway, so it just hangs and fails. It also means paying for a license to have Excel installed on the web server. If you use some other way to read the file you can avoid all of that.

Many people will just tell you how to fix the problem (including me) and that's good. But in return for doing all of the work to fix the problem you get a less-than-ideal solution with potential for still more problems. That's why I strongly recommend alternatives.

Community
  • 1
  • 1
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • How would I know when to call the release com objects when the excel workbook is manually close by user? –  May 13 '16 at 18:54