Just so you know, you can use GetObject to retrieve the actual document itself without the need to open an application and add a workbook. If the workbook is already open it will give you a reference to the already open instance, otherwise it will open it for you. This should allow you to avoid the issue ;)
Like:
Dim wb As Object
Set wb = GetObject("C:\book1.xlsx")
If not wb is nothing then debug.print wb.Name
You can access an existing instance of Excel using something like the below. You need to either add a reference to Microsoft Excel object library (Tools > References) or change the type of Dim xlapp
and Dim wb
to As Object
. I personally prefer to add the reference to keep intellisense and early binding / compiler checks.
'Gets an existing instance of Excel if running then closes workbooks open in the instance,
'otherwise exits
Sub blah()
Dim xlapp As Excel.Application
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
On Error GoTo 0
If xlapp Is Nothing Then
'No instance was running. You can create one with
'Set xlapp = New Excel.Application
'but in your case it doesn't sound like you need to so:
Exit Sub
End If
Dim wb As Workbook
For Each wb In xlapp.Workbooks
wb.Close False
Next wb
xlapp.Quit
End Sub
The process for getting a specific Application instance when multiple are running is very different so say if you need that requirement.