1

I am currently trying to create an export tool to push data into Excel. However after the first push, Excel is left open, and sometimes a user may want to leave Excel open while they push more data to another page in the same excel sheet. I usually just release the COM objects once the export is done. The way my methods work right now involves opening a new instance of excel every time I export...

would it be beneficial to create a global instance of the application to use continuiously from the point I begin exporting until the point of the Excel application being closed?

Should I be using event handlers to detect when Excel has been closed so I know when to release the COM objects?

If I do try to make a global instance of an Excel Application, I can instantiate it and wait to release it, that way I don't need to try and find open instances of excel again.. but if I needed to find, and assign to a variable, an open instance of Excel (that has previously existed in code but had the COM objects released), how would I do this?

meltdownmonk
  • 493
  • 2
  • 7
  • 17

2 Answers2

4

I have used this in the past. tPath is the path to my excel file that should be opened/reused.

Dim exApp As New Excel.Application

'finds the workbook.  If it is already open, then it uses that.  Otherwise, it opens in new instance
Dim wb As Excel.Workbook
wb = System.Runtime.InteropServices.Marshal.BindToMoniker(tPath)
exApp = wb.Parent
APrough
  • 2,671
  • 3
  • 23
  • 31
  • This seems to be what I'm looking for. Or it will best help when I am opening excel files, as I don't want the same one opening a second time.. – meltdownmonk Sep 05 '12 at 21:28
4

You can use the Interop Library to point to the open excel-app

(This code is written in C# so there could be some minor change for VB.Net)

oExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
Koen
  • 2,501
  • 1
  • 32
  • 43
  • The (Excel.Application) part is for casting? Otherwise this works just fine, I put and import statement in for it. I tried running a .Quit() function on the object right after and I got an error.. I'll play around a bit more before explaining the details.. – meltdownmonk Sep 05 '12 at 21:23
  • Yes, it's for casting (Sorry for the late answer), but it seems that your problem is already solved. ;-) – Koen Sep 06 '12 at 14:11