How to build an Office 2000 COM add-in in Visual Basic
This article was previously published under Q238228
This article has been archived. It is offered "as is" and will no longer be updated.
Microsoft Office 2000 and later support a new, uniform design architecture for building application add-ins to enhance and control Office applications. These add-ins are called COM Add-Ins. This article will demonstrate how to build a COM Add-In using Visual Basic.
A COM Add-In is an inprocess COM server (an ActiveX DLL) that implements the IDTExensibility2 interface as described in the Microsoft Add-In Designer Type Library (Msaddndr.dll). All COM add-ins inherit from this interface and must implement each of its five methods.
OnConnectionThe OnConnection event fires whenever the COM add-in is connected. The add-in may be connected on startup, by the end user, or through automation. If OnConnection returns successfully, the add-in is said to be loaded. If an error is returned, the host application immediately releases its reference to the add-in and the object is destroyed.
OnConnection takes the following four parameters:
- Application - A reference to the host application object.
- ConnectMode - A constant that specifies how the add-in was connected.
- ext_cm_AfterStartup - Started by the end user from the COM add-ins dialog box.
- ext_cm_CommandLine - Connected from the command line. (Does not apply to building COM add-ins for Office applications.)
- ext_cm_External - Connected by an external application through automation. (Does not apply to building COM add-ins for Office applications.)
- ext_cm_Startup - Started by the host at application startup. (This behavior is controlled by a setting in the registry.)
- AddInInst - A reference to the COMAddIn object that refers to this add-in in the COMAddIns Collection for the host application.
- Custom - An array of Variants that can hold user-defined data.
OnDisconnectionThe OnDisconnection event fires when the COM add-in is disconnected and just before it unloads from memory. The add-in should perform any cleanup of resources in this event, and restore any changes made to the host application.
OnDisconnection takes the following two parameters:
- RemoveMode - A constant that specifies how the add-in was disconnected.
- ext_dm_HostShutdown - Disconnected when the host application closed.
- ext_dm_UserClosed - Disconnected by the end user or an Automation controller.
- Custom - An array of Variants that can hold user-defined data.
OnAddInsUpdateThe OnAddInsUpdate event fires when the set of registered COM add-ins changes. In other words, whenever a COM add-in is installed or removed from the host application, this event fires.
OnStartupComplete and OnBeginShutdownBoth the OnStartupComplete and OnBeginShutdown methods are called when the host application has left or is entering a state where user-interaction should be avoided because the application is busy loading or unloading itself from memory. OnStartupComplete is only called if your add-in was connected during startup, and OnBeginShutdown is only called if your add-in is disconnected by the host during shutdown.
Because the user-interface for the host application is fully active when these events fire, they may be the only way to perform certain actions that otherwise would be unavailable from OnConnection and OnDisconnection.
Registering the COM add-inIn addition to normal COM registration, a COM add-in needs to register itself with each Office application in which it runs. To register itself with a particular application, the add-in should create a sub key, using its ProgID as the name for the key, under the following location:
The add-in can provide values at this key location for both a friendly display name and a full description. In addition, the add-in should specify its desired load behavior using a DWORD value called "LoadBehavior." This value determines how the add-in is loaded by the host application, and is made up of a combination of the following values:
- 0 = Disconnect - Is not loaded.
- 1 = Connected - Is loaded.
- 2 = Bootload - Load on application Startup.
- 8 = DemandLoad - Load only when requested by user.
- 16 = ConnectFirstTime - Load only once (on next startup).
Add-ins that implement IDTExtensibility2 should also specify a DWORD value called "CommandLineSafe" to indicate whether they are safe for operations that do not support a user interface. A value of 0x00 means False, 0x01 is True.
Building a COM add-inYou can build a COM Add-In in one of the three ways mentioned below:
Building a COM add-in by using the Com add-in TemplateIf you have Microsoft Office 2000 Developer or Microsoft Office XP Developer and Visual Basic 6.0, the easiest way to build a COM Add-in is to use the COM add-in.vbp template. This project is located in the ODETools\V9\Samples\OPG\Samples\CH11\VB_COM_AddIn subfolder on the Office 2000 Developer CD. Copy the files in this folder to the Visual Basic 6.0 Template\Projects folder, which is typically C:\Program Files\Microsoft Visual Studio\VB98\Template\Projects. Copying the template project to this location will ensure that the template appears in the Visual Basic 6.0 New Project dialog box. See Chapter 11 of the Microsoft Office 2000 Visual Basic Programmer's Guide for more information about this template and creating COM Add-ins.
Building a COM add-in by using the Visual Basic 6 add-in designerIf you have just Microsoft Visual Basic 6.0 installed and want to use a wrapper so that you don't need to directly implement IDTExtensibility2, you can use the same Add-In designer that you would use to build a VB6 Add-In. Follow these steps to build such an add-in for Microsoft Excel 2000 or 2002:
- Start Microsoft Visual Basic 6.0 and select Addin as the project type. This should add a designer class to the project (Connect) and a form (frmAddin).
- Open the Designer window for Connect and select Microsoft Excel from the Application drop-down list.
- In the Initial Load Behavior drop-down list, select Startup.
- Remove frmAddin from the project.
- From the Project window, right-click the Connect item and select view code.
- Remove all the code in the designer's code window. This code works for VB add-ins but not Office add-ins.
- Add the following code to the designer:
Option Explicit Dim oXL As Object Dim WithEvents MyButton As Office.CommandBarButton Private Sub AddinInstance_OnConnection(ByVal Application As Object, _ ByVal ConnectMode As AddInDesignerObjects.ext_ConnectMode, _ ByVal AddInInst As Object, custom() As Variant) On Error Resume Next MsgBox "My Addin started in " & Application.Name Set oXL = Application Set MyButton = oXL.CommandBars("Standard").Controls.Add(1) With MyButton .Caption = "My Custom Button" .Style = msoButtonCaption ' The following items are optional, but recommended. ' The Tag property lets you quickly find the control ' and helps MSO keep track of it when there is more than ' one application window visible. The property is required ' by some Office applications and should be provided. .Tag = "My Custom Button" ' The OnAction property is optional but recommended. ' It should be set to the ProgID of the add-in, such that if ' the add-in is not loaded when a user presses the button, ' MSO loads the add-in automatically and then raises ' the Click event for the add-in to handle. .OnAction = "!<" & AddInInst.ProgId & ">" .Visible = True End With End Sub Private Sub AddinInstance_OnDisconnection(ByVal RemoveMode As _ AddInDesignerObjects.ext_DisconnectMode, custom() As Variant) On Error Resume Next MsgBox "My Addin was disconnected by " & _ IIf(RemoveMode = ext_dm_HostShutdown, _ "Excel shutdown.", "end user.") MyButton.Delete Set MyButton = Nothing Set oXL = Nothing End Sub Private Sub MyButton_Click(ByVal Ctrl As Office.CommandBarButton, _ CancelDefault As Boolean) MsgBox "Our CommandBar button was pressed!" End Sub
- Save the project and create the MyAddin.dll. The designer will register the add-in for you.
- Open Microsoft Excel and you will notice a message box when the add-in is loaded and unloaded. On the standard toolbar, you will have a new button labeled My Custom Button that our add-in will handle when selected.
Building a COM add-in by using implementsWhile not as simple, you can create a COM Add-In using Microsoft Visual Basic 5.0 and the Implements keyword to directly implement the IDTExtensibility2 interface. The only downside to this approach is registration. Since Microsoft Visual Basic does not know how to add the keys needed to register the add-in with Office, you will need to do this separately (in a custom setup utility, or using a REG script).
However, the advantage to using Implements is that it is more direct and efficient than using the designer, and it allows us to create a single COM object that can work in multiple Office applications (instead of creating a separate Connect object for each application we want to work in).
Here are the steps for writing an Add-In using Implements:
- Open Visual Basic and create a new ActiveX DLL project. Name the project MyCOMAddin, and name the public class Connect.
- From the References dialog box (Project | References), add a reference to the Microsoft Office 9.0 (or 10.0 for Office XP) Object Library and the Microsoft Add-In Designer type library. If you cannot find the Add-In Designer in the References list, you should Browse for Msaddndr.dll or Msaddndr.tlb, typically located in the "C:\Program Files\Common Files\Designer" folder.
- In the Code window for Connect, add the following:
Option Explicit Implements IDTExtensibility2 Dim oHostApp As Object Dim WithEvents MyButton As Office.CommandBarButton Private Sub IDTExtensibility2_OnConnection(ByVal Application As Object, _ ByVal ConnectMode As AddInDesignerObjects.ext_ConnectMode, _ ByVal AddInInst As Object, custom() As Variant) On Error Resume Next ' Set a reference to the host application... Set oHostApp = Application ' If you aren't in startup, then manually call OnStartupComplete... If (ConnectMode <> ext_cm_Startup) Then _ Call IDTExtensibility2_OnStartupComplete(custom) End Sub Private Sub IDTExtensibility2_OnStartupComplete(custom() As Variant) Dim oCommandBars As Office.CommandBars Dim oStandardBar As Office.CommandBar On Error Resume Next ' Set up a custom button on the "Standard" commandbar... Set oCommandBars = oHostApp.CommandBars If oCommandBars Is Nothing Then ' Outlook has the CommandBars collection on the Explorer object Set oCommandBars = oHostApp.ActiveExplorer.CommandBars End If Set oStandardBar = oCommandBars.Item("Standard") If oStandardBar Is Nothing Then ' Access names it's main toolbar Database Set oStandardBar = oCommandBars.Item("Database") End If ' In case the button was not deleted, use the exiting one... Set MyButton = oStandardBar.Controls.Item("My Custom Button") If MyButton Is Nothing Then Set MyButton = oStandardBar.Controls.Add(1) With MyButton .Caption = "My Custom Button" .Style = msoButtonCaption ' The following items are optional, but recommended. ' The Tag property lets you quickly find the control ' and helps MSO keep track of it when there is more than ' one application window visible. The property is required ' by some Office applications and should be provided. .Tag = "My Custom Button" ' The OnAction property is optional but recommended. ' It should be set to the ProgID of the add-in, such that if ' the add-in is not loaded when a user presses the button, ' MSO loads the add-in automatically and then raises ' the Click event for the add-in to handle. .OnAction = "!<MyCOMAddin.Connect>" .Visible = True End With End If ' Display a simple message to know which application you started in... MsgBox "Started in " & oHostApp.Name & "." Set oStandardBar = Nothing Set oCommandBars = Nothing End Sub Private Sub IDTExtensibility2_OnDisconnection(ByVal RemoveMode As _ AddInDesignerObjects.ext_DisconnectMode, custom() As Variant) On Error Resume Next If RemoveMode <> ext_dm_HostShutdown Then _ Call IDTExtensibility2_OnBeginShutdown(custom) Set oHostApp = Nothing End Sub Private Sub IDTExtensibility2_OnBeginShutdown(custom() As Variant) On Error Resume Next ' Notify the user you are shutting down, and delete the button... MsgBox "Our custom Add-In is unloading." MyButton.Delete Set MyButton = Nothing End Sub Private Sub MyButton_Click(ByVal Ctrl As Office.CommandBarButton, CancelDefault As Boolean) MsgBox "Our CommandBar button was pressed!" End Sub Private Sub IDTExtensibility2_OnAddInsUpdate(custom() As Variant) 'You do nothing if this is called, but you need to 'add a comment so Visual Basic properly implements the function... End Sub
- Save the project and create the MyCOMAddin.dll. However, before your add-in will work you need to associate it with each Office application that you want it to run in. In the real world, a setup utility can do this when the DLL is installed. For this sample, you will call a registration function directly from the Visual Basic IDE.
- Add a new module to the project. In the code for Module1, add the following:
Option Explicit Private Declare Function RegCreateKeyEx Lib "advapi32.dll" _ Alias "RegCreateKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, _ ByVal Reserved As Long, ByVal lpClass As String, ByVal dwOptions As _ Long, ByVal samDesired As Long, ByVal lpSecurityAttributes As Long, _ phkResult As Long, lpdwDisposition As Long) As Long Private Declare Function RegSetValueEx Lib "advapi32.dll" _ Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As _ String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, _ ByVal cbData As Long) As Long Private Declare Function RegDeleteKey Lib "advapi32.dll" _ Alias "RegDeleteKeyA" (ByVal hKey As Long, ByVal lpSubKey As String) _ As Long Private Declare Function RegCloseKey Lib "advapi32.dll" _ (ByVal hKey As Long) As Long Private Const HKEY_CURRENT_USER = &H80000001 Private Const KEY_ALL_ACCESS = &H1F0037 Private Const REG_CREATED_NEW_KEY = &H1 Private Const REG_SZ = 1 Private Const REG_DWORD = 4 'These are the settings for your Add-in... Private Const PROGID As String = "MyCOMAddin.Connect" Private Const DESCRIPTION As String = "My VB5/6 COM Add-In Sample" Private Const LOADBEHAVIOR As Long = 3 Private Const SAFEFORCOMMANDLINE As Long = 0 Public Sub RegisterAll() RegisterOfficeAddin "Access" RegisterOfficeAddin "Excel" RegisterOfficeAddin "FrontPage" RegisterOfficeAddin "Outlook" RegisterOfficeAddin "PowerPoint" RegisterOfficeAddin "Word" End Sub Public Sub UnregisterAll() UnRegisterOfficeAddin "Access" UnRegisterOfficeAddin "Excel" UnRegisterOfficeAddin "FrontPage" UnRegisterOfficeAddin "Outlook" UnRegisterOfficeAddin "PowerPoint" UnRegisterOfficeAddin "Word" End Sub Public Sub RegisterOfficeAddin(sTargetApp As String) Dim sRegKey As String Dim nRet As Long, dwTmp As Long Dim hKey As Long sRegKey = "Software\Microsoft\Office\" & sTargetApp _ & "\Addins\" & PROGID nRet = RegCreateKeyEx(HKEY_CURRENT_USER, sRegKey, 0, _ vbNullString, 0, KEY_ALL_ACCESS, 0, hKey, dwTmp) If nRet = 0 Then If dwTmp = REG_CREATED_NEW_KEY Then Call RegSetValueEx(hKey, "FriendlyName", 0, _ REG_SZ, ByVal PROGID, Len(PROGID)) Call RegSetValueEx(hKey, "Description", 0, _ REG_SZ, ByVal DESCRIPTION, Len(DESCRIPTION)) Call RegSetValueEx(hKey, "LoadBehavior", 0, _ REG_DWORD, LOADBEHAVIOR, 4) Call RegSetValueEx(hKey, "CommandLineSafe", 0, _ REG_DWORD, SAFEFORCOMMANDLINE, 4) End If Call RegCloseKey(hKey) End If End Sub Public Sub UnRegisterOfficeAddin(sTargetApp As String) Dim sRegKey As String sRegKey = "Software\Microsoft\Office\" & sTargetApp _ & "\Addins\" & PROGID Call RegDeleteKey(HKEY_CURRENT_USER, sRegKey) End Sub
- From the Immediate window (View | Immediate Window), type RegisterAll, and then press ENTER. This will register the add-in with all the Office applications supported (Access, Excel, FrontPage, Outlook, PowerPoint, and Word).
- Open any of the Office applications listed prior. Notice the message box on startup and shutdown, and the custom button added to standard toolbar.
- When you want to unregister the add-in, type UnregisterAll in the Visual Basic Immediate window and then press ENTER.
"Microsoft Office 2000 Visual Basic Programmer's Guide", Chapter 11. Add-ins, Templates, Wizards, and Libraries.
For more information about writing COM add-ins, click the following article numbers to view the articles in the Microsoft Knowledge Base:
230689 SAMPLE: Comaddin.exe Office 2000 COM add-in written in Visual C++
190253 VB6 designers do not work in VB5For more information about developing Web-based solutions for Microsoft Internet Explorer, visit the following Microsoft Web site:Note When you add a menu item to Office Word from a Visual Basic COM add-in by using the steps that are listed in this article or by using a similar method, the menu item does not work as expected. For more information, click the following article number to view the article in the Microsoft Knowledge Base:
313948 Word loses reference to COM object menu items (CommandBarControl)
Article ID: 238228 - Last Review: 12/05/2015 15:21:11 - Revision: 6.2
Microsoft Excel 2000 Standard Edition, Microsoft Office XP Developer Edition, Microsoft Office 2000 Developer Edition, Microsoft Access 2002 Standard Edition, Microsoft Access 2000 Standard Edition, Microsoft Excel 2002 Standard Edition, Microsoft FrontPage 2002 Standard Edition, Microsoft FrontPage 2000 Standard Edition, Microsoft Outlook 2002 Standard Edition, Microsoft Outlook 2000 Standard Edition, Microsoft PowerPoint 2002 Standard Edition, Microsoft PowerPoint 2000 Standard Edition, Microsoft Word 2002, Microsoft Word 2000, Microsoft Visual Basic 5.0 Professional Edition, Microsoft Visual Basic 6.0 Professional Edition, Microsoft Visual Basic 5.0 Enterprise Edition, Microsoft Visual Basic Enterprise Edition for Windows 6.0
- kbnosurvey kbarchive kbautomation kbhowto KB238228