Build Excel, Word, PowerPoint add-in
for Office 2016, 2013, 2010, 2007 in Delphi

Add-in Express™
for Microsoft® Office and Delphi® VCL

Add-in Express Home > Add-in Express for Office and Delphi VCL > Online Guide > Creating Office add-in in Delphi

Developing Office COM add-in in Delphi

This page highlights almost every aspect of creating COM add-ins for Microsoft Office 2016 - 2000 applications, namely adding a custom button to Office commandbar, customizing the Ribbon interface, creating task panes, handling host application events and more. The sample project described below implements a COM add-in for Excel, Word and PowerPoint. It is included in Add-in Express for Office and VCL sample projects available on the Downloads page.

Add-in Express provides additional components for Outlook COM Add-ins. See Building Outlook plug-ins.

Step 1. Creating a COM Add-in project

Make sure that you have administrative permissions before running Delphi. Also, if you have Windows Vista, Windows 7, Windows Server 2008 or Windows 8, run Delphi via Run as Administrator.

Add-in Express adds the COM Add-in project template to the New Items dialog.

Creating a new Office add-in project in Delphi

When you select the template and click OK, the COM Add-in Wizard starts. In the wizard windows, you choose the project options.

COM add-in wizard

The wizard creates and opens your project in the Delphi IDE.

Office COM Add-in project in Delphi

The COM add-in project includes the following items:

  • Project source files: (ProjectName.*)
  • Type library file: (ProjectName_TLB.pas)
  • Add-in module (ProjectName_IMPL.pas and ProjectName_IMPL.dfm) discussed in the following step

Step 2. COM Add-in module

The add-in module (MyAddin1_IMPL.pas and MyAddin1_IMPL.dfm) is the core component of the COM add-in project. It is a container for Add-in Express components. You specify the add-in properties in the module's properties, add the required components to the module's designer, and write the functional code of your add-in in this module.

The code for MyAddin1_IMPL.pas is as follows:


unit MyAddin1_IMPL;

interface

uses
  SysUtils, ComObj, ComServ, ActiveX, Variants, Office2000, adxAddIn, 
  MyAddin1_TLB;

type
  TcoMyAddin1 = class(TadxAddin, IcoMyAddin1)
  end;

  TAddInModule = class(TadxCOMAddInModule)
    procedure adxCOMAddInModuleAddInInitialize(Sender: TObject);
    procedure adxCOMAddInModuleAddInFinalize(Sender: TObject);
  private
  protected
  public
  end;
var
  adxcoMyAddin1: TAddInModule;

implementation

{$R *.dfm}

procedure TAddInModule.adxCOMAddInModuleAddInInitialize(Sender: TObject);
begin
  adxcoMyAddin1 := Self;
end;

procedure TAddInModule.adxCOMAddInModuleAddInFinalize(Sender: TObject);
begin
  adxcoMyAddin1 := nil;
end;

initialization
  TadxFactory.Create(ComServer, TcoMyAddin1, CLASS_coMyAddin1,
  TAddInModule);
end. 

The add-in module contains two classes: the "interfaced" class (TcoMyAddin1 in this case) and the add-in module class (TAddInModule). The "interfaced" class is a descendant of the TadxAddIn class that implements the IDTExtensibility2 interface required by the COM Add-in architecture. Usually, you don't need to change anything in the TadxAddIn class.

The add-in module class implements the add-in functionality. It is an analogue of the Data Module, but unlike the Data Module, the add-in module allows you to set all properties of your Office add-in, handle its events, and create toolbars and controls.

Step 3. COM Add-in designer

The COM Add-in module allows setting add-in properties and adding components to the module. Click the module's designer surface, activate Object Inspector, choose the SupportedApps property and select Excel, Word, and PowerPoint.

Configuring the add-in's properties in the COM Add-in module

You can find the Add-in Express components in the Tool Palette. See also Add-in Express for Office and Delphi components.

Step 4. Adding a new command bar

To add a command bar to your Office add-in, find the TadxCommandBar component in the Tool Palette and drag-n-drop it onto the TadxCOMAddinModule designer.

Adding a new commandbar component to the add-in module

Select the command bar component and, in the Object Inspector window, specify the command bar name using the CommandBarName property. Also, you select its position in the Position property.

Note. To display a command bar on the Office 2007 - 2016 Ribbon, you must explicitly set the UseForRibbon property of the command bar component to True. The controls added to such a command bar will be shown on the built-in Ribbon tab called Add-ins.

Step 5. Adding a new command bar button

To add a new button to a command bar, in the Object Inspector window, you run the property editor of the Controls property for an appropriate command bar component. The property editor is a simple and easy designer of command bars and their controls.

Adding a new button to the Office command bar

Specify the button's Caption property and set the Style property to adxMsoButtonIconAndCaption (default value = adxMsoButtonAutomatic). In the Object Inspector window, you switch to the Events tab to add the OnClick event handler for the command bar button component.

Step 6. Accessing host application objects

The Add-in Module provides the HostApplication property that returns the Application object (of the OleVariant type) of the host application the add-in is currently running in. For your convenience, Add-in Express provides the <HostName>App properties, say ExcelApp of the TExcelApplication type and WordApp of the TWordApplication type. Together with the HostType property, this allows us to write the following code to the Click event of newly added button.


procedure TAddInModule.DefaultAction(Sender: TObject);
begin
  ShowMessage(GetInfoString());
end;

function TAddInModule.GetInfoString(): string;
var
  er: ExcelRange;
  IWindow: IDispatch;
begin
  Result := 'No document window found!';
  try
    // Word raises an exception if there's no document open
    IWindow := HostApp.ActiveWindow;
  except
  end;
  try
    if IWindow <> nil then
      case HostType of
        ohaExcel:
          try
            er := (IWindow as Excel2000.Window).ActiveCell;
           //relative address
            Result := 'The current cell is: '
              +  er.AddressLocal[False, False, xlA1, EmptyParam, EmptyParam]; 
          finally
            er := nil;
          end;
        ohaWord:
          Result := 'The current selection contains '
            + IntToStr(
              (IWindow as Word2000.Window).Selection.Range.Words.Count)
            + ' words';
        ohaPowerPoint:
          Result := 'The current selection contains '
            + IntToStr(
              (IWindow as MSPpt2000.DocumentWindow).Selection.SlideRange.Count)
            + ' slides';
      else
        Result :=  'The ' + AddinName 
          + ' COM Add-in doesn''t support the current host application!' ;
      end;
  except
  end;
  IWindow := nil;
end;

Step 7. Customizing main menus of Excel, Word, PowerPoint

Add-in Express provides a component to customize main menus in Office applications (but see Developing Microsoft Outlook COM add-in for customizing Outlook menu bar). Some applications from Office 2000-2003 have several main menus. Say, in these Excel versions, you find Worksheet Menu Bar and Chart Menu Bar. Naturally, in Excel 2007, 2010, 2013 and 2016 these menus are replaced with the Ribbon UI. Nevertheless, they are still accessible programmatically and you may want to use this fact in your code.

In this sample, we are going to customize the File menu in Excel and Word version 2000-2003. You start with adding two main menu components (TadxMainMenu) and specifying correct host applications in their SupportedApp properties. Then, in the CommandBarName property, you specify the main menu.

The screenshot below shows how you set up the main menu component in order to customize the Worksheet Menu Bar main menu in Excel 2003 - 2000.

Setting the properties of the Main Menu component

The TadxMainMenu.Controls property provides a designer that allows adding custom controls to a set of predefined popup controls that corresponds to built-in main menu items such as File, Edit, etc. Those popups demonstrate the main principle of referencing built-in command bar controls: if the OfficeID property of a commandbar control component is other than 1, you are referencing the corresponding built-in control. You can find the IDs of built-in command bar controls using the free Built-in Controls Scanner utility.

Customizing the Excel main menu at design-time

In the source code of the sample add-in described here, you can find how you can customize the Office Button menu in Office 2007 (see the component named adxRibbonOfficeMenu1). As to the Backstage View, also known as a File tab in Office 2010, 2013, and 2016, the sample projects provide the adxBackstageView1 component that implements the customization shown in Figure 3 at Introduction to the Office 2010 Backstage View for Developers. Note, if you customize the Office Button menu only, Add-in Express maps your controls to the Backstage View. If, however, both Office Button menu and File tab are customized at the same time, Add-in Express ignores custom controls you add to the Office Button menu.

Step 8. Customizing context menus of Excel, Word, PowerPoint

Add-in Express allows customizing commandbar-based context menus of Office 2000 - 2016 applications with the TadxContextMenu component. Its use is similar to that of the TadxMainMenu component. To set up such a component to add a custom button to an Office context menu, you do the following: :

  • Add a context menu component to the add-in module
  • Specify the host application, the context menu of which you need to customize.
  • In the component's properties choose the host application and the context menu to be customized.
  • Use the editor of the Controls collection to populate the context menu with custom controls.

The screenshot below demonstrates adding a custom item to the context menu Cells in Excel.

Customizing the Excel context menu

You may want to use the OnBeforeAddControls event provided by the component to modify the context menu depending on the current context. Say, custom controls in the context menu may reflect the content of an Excel cell, the current chapter of the Word document, etc.

There are several issues related to using command bar based context menus:

  • Excel contains two different context menus named Cell. This fact breaks down the command bar development model because the only way to recognize two command bars is to compare their names. This isn't the only exception: see the Built-in Controls Scanner utility to find a number of examples. In this case, the context menu component cannot distinguish context menus. Accordingly, it connects to the first context menu with the specified name.
  • Command bar based context menu items cannot be positioned in the Ribbon-based context menus: a custom context menu item created with the ADXContextMenu component will always be shown below the built-in and custom context menu items in a Ribbon-based context menu of Office 2010, 2013 and 2016.

To add a custom item to a context menu in Office 2010, 2013 and 2016, you use the TadxRibbonContextMenu component. Unlike its commandbar-based counterpart (TadxContextMenu), this component allows adding the same custom controls to several context menus in the specified Ribbon. Say, the screenshots below demonstrate component settings required for adding a control to the ExcelWorkbook Ribbon. To specify the context menus to which the control will be added, you use the editor of the ContexMenuNames property of the component.

Setting the properties of the Ribbon Context Menu component

Specifying the names of the context menus

Step 9. Handling host application events

Add-in Express supplies several components that provide application-level events for the add-in module. To handle Excel events to the add-in, drop a TadxExcelAppEvents onto the module. Naturally, handling Word events requires using a TadxWordAppEvents while TadxPowerPointAppEvents provides PowerPoint application-level events.

With the above components, you can handle any application-level events of the host application. Say, you may want to disable a button when a window deactivates and enable it when a window activates. The code processing the PowerPoint version of the WindowActivate and WindowDeactivate events is as follows:



procedure TAddInModule.adxExcelAppEvents1WindowActivate(ASender: TObject;
 const Wb: _Workbook; const Wn: Window);
begin
    adxCommandBar1.Controls[0].Enabled := true;
end;

procedure TAddInModule.adxExcelAppEvents1WindowDeactivate(ASender: TObject;
 const Wb: _Workbook; const Wn: Window);
begin
    adxCommandBar1.Controls[0].Enabled := false;
end;

procedure TAddInModule.adxWordAppEvents1WindowActivate(ASender: TObject;
 const Doc: _Document; const Wn: Window);
begin
    adxCommandBar1.Controls[0].Enabled := true;
end;

procedure TAddInModule.adxWordAppEvents1WindowDeactivate(ASender: TObject;
 const Doc: _Document; const Wn: Window);
begin
    adxCommandBar1.Controls[0].Enabled := false;
end;

Note. It is possible to create a set of event handlers and connect it to any given Excel worksheet. You can do this by adding a TExcelWorksheet (Tool Palette, the Servers tab) onto the add-in module.

Step 10. Customizing the Office Ribbon user interface

To add a new tab to the Office 2007 - 2016 Ribbon, you add the TadxRibbonTab component to the module.

Adding a new ribbon tab with a custom button

In the Object Inspector window, run the editor for the Controls collection of the tab. In the editor, use the toolbar buttons or context menu to add or delete Add-in Express components that form the Ribbon interface of your add-in. First, you add a Ribbon tab and change its caption to My Ribbon Tab. Then, you select the tab component, add a Ribbon group, and change its caption to My Ribbon Group. Next, you select the group, and add a button group. Next, you select the group, and add a button. Set the button caption to My Ribbon Button. Use the Glyph property to set the icon for the button.

Now write the following code in the OnClick event handler of the newly added Ribbon button (the code below refers to the code added in Step 6. Accessing Host Application Objects):


procedure TAddInModule.adxRibbonTab1Controls0Controls0Controls0Click(
  Sender: TObject; const RibbonControl: IRibbonControl);
begin
  DefaultAction(nil);
end;

Remember, the TadxRibbonTab Controls editor performs the XML-schema validation automatically, so from time to time you will run into the situation when you cannot add a control to some Ribbon level. It is a restriction of the Ribbon XML-schema.

Step 11. Adding custom task panes in Excel 2000 - 2016

To add a new task pane to Outlook, Excel, Word and PowerPoint, you do the following:

  • add an Excel Task Panes Manager (TadxExcelTaskPanesManager) to your add-in module
  • add an Add-in Express Excel Task Pane (TadxExcelTaskPane) to your project
  • in the visual designer available for the Controls collection of the manager, add an item to the collection, bind the pane to the item and specify its properties as shown on the screenshot

Below is the description of the settings:

  • AlwaysShowHeader - specifies that the pane header will be shown even if the pane is the only one in the current region.
  • CloseButton - specifies if the Close button is shown in the pane header. Obviously, there isn't much sense in setting this property to true when the header is not shown.
  • Position - specifies the region in which an instance of the pane will be shown. Excel panes are allowed in four regions docked to the four sides of the main Excel window: pRight, pBottom, pLeft, and pTop. The fifth region is pUnknown.
  • TaskPaneClassName - specifies the class name of the Excel task pane.

Configuring an advanced Excel custom task pane

Now you add a label onto your custom task pane and add an event handler for the OnADXBeforeTaskPaneShow event:


procedure TadxExcelTaskPane1.adxExcelTaskPaneADXBeforeTaskPaneShow(
  ASender: TObject; Args: TadxBeforeTaskPaneShowEventArgs);
begin
  Label1.Caption := (AddinModule as TAddInModule).GetInfoString();
end;

See Advanced Excel Task Panes for more information.

Step 12. Adding custom task panes for PowerPoint 2000 - 2016

To add a PowerPoint task pane:

  • add a PowerPoint Task Panes Manager (TadxPowerPointTaskPanesManager) to your add-in module
  • add an Add-in Express PowerPoint Task Pane (TadxPowerPointTaskPane) to your project
  • in the visual designer available for the Controls collection of the manager, add an item to the collection, bind the pane to the item and specify the appropriate value in the Position.

Now add a label onto the form, and update the label in the OnADXBeforeTaskPaneShow event handler of the form:


procedure TadxPowerPointTaskPane1.adxPowerPointTaskPaneADXBeforeTaskPaneShow(
  ASender: TObject; Args: TadxBeforeTaskPaneShowEventArgs);
begin
  Label1.Caption := (AddinModule as TAddInModule).GetInfoString();
end;

Step 13. Adding custom task panes for Word 2000 - 2016

You add a Word task pane in the same manner:

  • add a Word Task Panes Manager (TadxWordTaskPanesManager) to your add-in module
  • add an Add-in Express Word Task Pane (TadxWordTaskPane) to your project
  • in the visual designer available for the Controls collection of the manager, add an item to the collection, bind the pane to the item and specify an appropriate value in the Position

When the item's properties are set, you add a label onto the form, and write the code that updates it in the OnADXBeforeTaskPaneShow event handler of your form:


procedure TadxWordTaskPane1.adxWordTaskPaneADXBeforeTaskPaneShow(
  ASender: TObject; Args: TadxBeforeTaskPaneShowEventArgs);
begin
  Label1.Caption := (AddinModule as TAddInModule).GetInfoString();
end;

Step 14. Running your Office COM add-in

Save the add-in project, compile it, close all applications that you have selected as add-in host a pplications, and register the add-in via "Run | Register ActiveX Server". Run one of the selected host applications, find your toolbar and click the button.

The newly created add-in in Word 2010:

The add-in's UI in Word 2010

The newly created add-in in Excel 2010:

The add-in's UI in Excel 2010

The newly created add-in in PowerPoint 2010:

The add-in's UI in PowerPoint 2010

Step 15. Debugging the COM add-in

To debug your add-in, just indicate the add-in host application in the Host Application field in the Project Options window.

Specifying the parameters to debug your add-in

To debug your add-in in an Office 2010, 2013 and 2016 64-bit application, you have to register the add-in DLL using regsvr32; run it from an elevated 64-bit Command Prompt. In addition, you must explicitly specify to run the 64-bit application in the dialog window shown above.

Step 16. Deploying the COM add-in

Make sure your setup project registers the add-in DLL. Say, in Inno Setup projects you use the 'regserver' command.

Add-in Express for Office and Delphi <<

>> Building Outlook plugins in Delphi