To determine if an Office app is already running or not we can just error trap its attachment error.

The reasons for reusing an app instance is for performance and optimizations of your app.

For example, if you wanted to add a new workbook to an already running instance of Excel you would just use GetObject to set your app object variable to it. But the issue is that you can not depend on it always already existing. So for that we just trap the error and if raised we can make a call to the CreateObject function to start a new instance of our desired Office app.

Also, by declaring our application object variable as "Object" we can support multiple versions of the Office app as we are using Late Binding.

You can substitute "Excel.Application" in the example with any Office .Application class type. Ie: Access, Word, Outlook, etc.


VB 6 And Excel 97-2007 Code Example:

VB Code:
  1. Option Explicit
  2. 'Define our application object variable using Late Binding
  3. Private oApp As Object
  4.  
  5. Private Sub Form_Load()
  6.     'Designate our error handling procedure
  7.     On Error GoTo MyError
  8.     'Test the attachment of any possible already running instances our our desired Office app
  9.     'If unsecussful then it will direct the code to execute the error handler - "MyError"
  10.     Set oApp = GetObject(, "Excel.Application")
  11.     'Test if it failed
  12.     If TypeName(oApp) = "Nothing" Then
  13.         'If it gets to here then we have been returned from the error handler
  14.         'So we will want to create a new instance of the application object
  15.         Set oApp = CreateObject("Excel.Application")
  16.     End If
  17.     Exit Sub
  18. MyError:
  19.     'Test for the error being "Cant create object"
  20.     If Err.Number = 429 Then
  21.         'It is so lets return to the next line of code to create a new instance of the app object
  22.         'Its possible that this could be executed twice if the CreateObject line fails
  23.         'In which case that would mean the Office app is not installed or such.
  24.         Resume Next
  25.     Else
  26.         'It was another type of error so lets display it to the user
  27.         MsgBox Err.Number & " - " & Err.Description, vbOKOnly + vbExclamation
  28.     End If
  29. End Sub