Working with Host Application Object Models

There are a few things to keep in mind as you add forms and other components to your COM add-in. First, your COM add-in is similar to a separate application running inside a Microsoft® Office XP application. Therefore, you must set references to any object libraries you want to work with from within the COM Add-in project. If your add-in will be run in more than one application, you can use the OnConnection event procedure to determine which application your add-in is currently running in and then selectively run code that works with that application's objects.

To figure out which application the add-in is currently running, use the object supplied by the Application argument of the OnConnection event procedure. Assign this object variable to a global object variable. In the code that interacts with the host application, check to see which application you are working with, and use that application's object model to perform the task.

A DLL is loaded into memory only once, but each application that accesses the DLL gets its own copy of the DLL's data, stored in a separate space in memory. Therefore, you can use global variables in a COM add-in without worrying about data being shared between two applications that are using the COM add-in at the same time. For example, the Image Gallery sample add-in can run simultaneously in Microsoft® Word, Microsoft® Excel, and Microsoft® PowerPoint®. When Word loads the add-in, the OnConnection event occurs and a reference to the Word Application object is stored in a global variable of type Object. If Excel then loads the add-in, the OnConnection event occurs and a reference to the Excel Application object is stored in a global variable of type Object but in a different space in memory. Within the code for the add-in, you can use the If TypeOfEnd If construct to check to which application's Application object the variable points.

' Global object variable, declared in modSharedCode module.
Public gobjAppInstance As Object

Private Sub cmdInsert_Click()
   ' Insert selected image.
   ' Check which object variable has been initialized.
   If TypeOf gobjAppInstance Is Word.Application Then
      ' Insert into Word.
      Word.Selection.InlineShapes.AddPicture FileName:= _
         img(mlngSel).Tag, LinkToFile:=False, _
         SaveWithDocument:=True
   ElseIf TypeOf gobjAppInstance Is Excel.Application Then
      gobjAppInstance.ActiveSheet.Pictures.Insert img(mlngSel).Tag
   ElseIf TypeOf gobjAppInstance Is Powerpoint.Application Then
      gobjAppInstance.ActiveWindow.Selection.SlideRange.Shapes.AddPicture _
         FileName:=img(mlngSel).Tag, LinkToFile:=msoFalse, _
         SaveWithDocument:=msoCTrue, Left:=100, Top:=100
   End If 
End Sub

See Also

Working with Add-in Designers | Configuring an Add-in Designer | Creating COM Add-ins for Multiple Applications