What's New | Articles | Message Board | Links | Code Snippets | Code Downloads | Toolbox | Books

Creating a VB Add-in

This article will step you though the process of a creating an add-in for Visual Basic.  Add-ins are useful as they allow you to automate common tasks so instead of typing heaps of code you can get the basis of what you need done with a click of the mouse.  They can also be used to perform such tasks as code indenting and moving controls on a form.

The Add-in we will be creating will allow a form or selected controls on a form to scaled by a given percentage.  This will demonstrate how to access controls on a form and get and set their properties.

The code for this add-in was written for Visual Basic 5.0.

Using Add-ins

Visual Basic comes with a number of add-ins some are no more than standalone programs that are available from the Add-Ins menu such as the API Viewer.   Others integrate with VB more like the VB Application Wizard.

Add-ins are loaded using the Add-In manager available from the Add-ins menu.  When the add-in is loaded it is available though the Add-Ins menu or a toolbar.

addinmanager.gif (17840 bytes)The list of Add-ins in the Add-in Manager comes from the file VBAddin.INI in the windows directory.  This file contains the progID (Project and class name) of the add-in and weather it is loaded when Visual Basic starts.

Figure 1 VBAddin.ini

Our program will have to edit this file so that our add-in is displayed in this list.



Control Scalar Add-inaddin.jpg (21840 bytes)

The Control Scalar add-in loops though each control in the active form and scales it by the specified amount.  The form for this add-in is shown on the right.

Now we know what we're aiming for how do we get there?

There are 6 main steps to creating this Add-in:

  1. Creating & Setting the Project Options
  2. Creating the Add-In Class
  3. Creating the user-interface
  4. Setting the name displayed in Add-In Manager
  5. Testing the Add-in
  6. Creating the Server DLL

1. Creating & Setting the Project Options

Start Visual Basic and create a new ActiveX DLL Project.  From the Project menu select Project1 Properties...

wpe25.jpg (26982 bytes)

From the Project Properties dialog set the Project Name to "ControlScalarAddin" as shown above and click OK.

wpe28.jpg (28401 bytes)

Add-in classes need to implement the IDTExtensibility interface so that Visual Basic can call the required subs IDTExtensibility_OnConnection, IDTExtensibility_OnAddInsUpdate,IDTExtensibility_OnDisconnection and IDTExtensibility_OnStartupComplete.  To you the programmer these subs act like events.

To do this select References from the Project menu and make sure "Microsoft Visual Basic 5.0 Extensibility" is checked.  To control Visual Basics menus and toolbars we need the "Microsoft Office 8.0 Object Library" so check that too.

2. Creating the Add-In Class

A new class should have been created when you created the ActiveX DLL if not add a new class to the project now.

wpe27.jpg (10398 bytes)

Set the name of the class to "Connect" and Instancing to 5 - MultiUse.

Now we need some code.  Paste the code given below into the General Declarations section of the Connect class.

Option Explicit

Implements IDTExtensibility

Public FormDisplayed As Boolean
Public VBInstance As VBIDE.VBE
Dim mcbMenuCommandBar As Office.CommandBarControl
Dim frmAddIn As New frmAddIn
Public WithEvents MenuHandler As CommandBarEvents 'command bar event handler

When the user of this addin selects it in the Add-In manager the IDTExtensibility_OnConnection sub will be called.  A VBInstance is passed and this is used to access the Visual Basic environment.  This is needed as more than one copy of VB can be running at a time.  All aspects of the VB environment such as project,forms, tools bars, etc can be accessed though this object.  Copy the code below and paste it into the class.

Private Sub IDTExtensibility_OnConnection(ByVal VBInst As Object, ByVal ConnectMode As vbext_ConnectMode, ByVal AddInInst As VBIDE.AddIn, custom() As Variant)

On Error GoTo error_handler

'save the vb instance
Set VBInstance = VBInst

If ConnectMode = vbext_cm_External Then
  'Used by the wizard toolbar to start this wizard
' A Sub we will write that adds an item
  'to the Add-in menu and returns a reference to the menu item.
  Set mcbMenuCommandBar = AddToAddInCommandBar(App.Title)

  'The MenuHandler object handles when the user clicks on the menu
  Set Me.MenuHandler = VBInst.Events.CommandBarEvents(mcbMenuCommandBar)
End If

If ConnectMode = vbext_cm_AfterStartup Then
  If GetSetting(App.Title, "Settings", "DisplayOnConnect", "0") = "1" Then
    'set this to display the form on connect
    Me.Show ' A Sub we will write
  End If
End If

Exit Sub


MsgBox Err.Description

End Sub

The addin also needs a way to clean up after it's self.  The code that does this is placed in the IDTExtensibility_OnDisconnection sub.

'this method removes the Add-In from VB
Private Sub IDTExtensibility_OnDisconnection(ByVal RemoveMode As vbext_DisconnectMode, custom() As Variant)
On Error Resume Next

'delete the command bar entry

'shut down the Add-In
If FormDisplayed Then
  SaveSetting App.Title, "Settings", "DisplayOnConnect", "1"
  FormDisplayed = False
  SaveSetting App.Title, "Settings", "DisplayOnConnect", "0"
End If

Unload mfrmAddIn
Set mfrmAddIn = Nothing
End Sub

If their is anything that needs to be done after the addin is loaded it is placed in the IDTExtensibility_OnStartupComplete sub.  In this example code is placed in this sub so that the add-in's form will be displayed when the add-in loads if the form was open last time the add-in was disconnected.  Whether or not the form is to be displayed is stored in the registry after being written there from the IDTExtensibility_OnDisconnection sub.

Private Sub IDTExtensibility_OnStartupComplete(custom() As Variant)
  If GetSetting(App.Title, "Settings", "DisplayOnConnect", "0") = "1" Then
    'set this to display the form on connect
  End If
End Sub

When you implement an interface you need to provide implementations for each method.   So even thou this sub won't be used we need to add it.

Private Sub IDTExtensibility_OnAddInsUpdate(custom() As Variant)
' To stop the sub being removed by the compiler.
End Sub

The following sub routines are used in this class.  There's nothing special about them they are just called from the subs shown above

' Adds an item to the Add-in menu
Function AddToAddInCommandBar(sCaption As String) As
      Dim cbMenuCommandBar As Office.CommandBarControl 'command bar object
      Dim cbMenu As Object      

      On Error GoTo AddToAddInCommandBarErr    

      'see if we can find the Add-Ins menu
      Set cbMenu = VBInstance.CommandBars("Add-Ins")

      If cbMenu Is Nothing Then
        'not available so we fail
        Exit Function
      End If      

      'add it to the command bar
      Set cbMenuCommandBar = cbMenu.Controls.Add(1)

      'set the caption
      cbMenuCommandBar.Caption = sCaption
      Set AddToAddInCommandBar = cbMenuCommandBar

      Exit Function


End Function

Sub Hide()
  On Error Resume Next
  FormDisplayed = False
End Sub

Sub Show()
  On Error Resume Next
  If mfrmAddIn Is Nothing Then
    Set mfrmAddIn = New frmAddIn
  End If

  Set mfrmAddIn.Connect = Me
  FormDisplayed = True
  mfrmAddIn.Show vbModal

End Sub

To make the add-in display it's self when it is selected from the menu we add Me.show to the MenuHandler's click event.  MenuHandler is an instance of CommandBarEvents and is associated with our menu item in the IDTExtensibility_OnConnection sub.

'this event fires when the menu is clicked in the IDE
Private Sub MenuHandler_Click(ByVal CommandBarControl As Object, handled As Boolean, CancelDefault As Boolean)
End Sub

3. Creating the User-Interface

We have created a class that connects with VB environment and sets up the menu and handles it's click event. Much of this code will be the same for any Add-in you create.   Now we will add a form that will do the work (scaling the controls).

From the Project menu select Add Form and add a blank form to the project.   Rename this form "frmAddIn".

Add the following controls to the form:

Name Type Caption
txtHorizontal Text Box  
txtVertical Text Box  
chkScaleForm Check Box &Scale Form as well
optScaleSelectedControls Option Box Scale selected controls
optScaleAll Option Box Scale &all controls
OKButton Command Button OK
CancelButton Command Button Cancel

You can also add labels to for the textboxes as shown in picture at the start of this article.

In the General Declarations section of the form add the following code:

I've comment most of the above code that does the scaling.  All the scaling is done in the Click event of "OKButton".

Properties aren't set in the usual way but though the Properties collection of the VBControl object.  We can get/set any property of a control using the properties collection. e.g. If we want to  set the name of each control to its current name with a one appended to the end we would type:

ourVBControl.Properties("name") = ourVBControl.Properties("name") & "1"

4. Setting the Name displayed in the add-in manager

To set the name that is display in the Add-in Manager press F2 to start the Object Browser.  Select the name of the project("ControlScalarAddin") in the first combo box.  Right click on the Connect class and click properties.   In the box that is displayed enter "Control Scalar Add-in" as the description and click Ok and then close the Object Browser.

Object Browser
Changing the name displayed in the add-in manager through the Object Browser.

5. Testing the Add-in

Now all there is left to do is to test the addin.

Because Add-ins run inside the VB environment the testing procedures are a little different than testing regularly applications.

As you learnt earlier an entry for our addin must be placed in the VBAddin.ini.  We could do this using a text editor or we can use the WritePrivateProfileString API to do it for us. Create a new module and paste the following code into it.

Option Explicit
Declare Function WritePrivateProfileString& Lib "Kernel32" Alias "WritePrivateProfileStringA" (ByVal AppName$, ByVal KeyName$, ByVal keydefault$, ByVal FileName$)

Sub AddToINI()
  Dim ErrCode As Long

  ' The following code will add
  ' ControlScalarAddin.Connect=0
  ' to the vbaddin.ini file. 
  ErrCode = WritePrivateProfileString("Add-Ins32", "ControlScalarAddin.Connect", "0", "vbaddin.ini")
End Sub

* Notice that ControlScalarAddin.Connect is the name of the project and the name of the class that VB will connect to.

To execute the AddToINI sub select the Immediate window from the view menu.  In the Immediate window type AddToIni and press enter.  This will add the entry to VBaddin.ini.  This could be done in the setup program for your add-in.

Add-ins are tested by running them and starting another instance of VB so press F5 to run your addin, when it is running start a second instance of Visual Basic.  Select Control Scalar Add-in from the addin manager and click OK.  You should now be able to run your addin by selecting it from the Add-Ins menu.  In the first instance of VB you can pause the add-in and step though it line by line just like any other program.

When you are done testing it start the Add-In manager again and unselect your addin and than stop it in the original instance of VB.

6. Creating the Server DLL

You compile the add-in just like any other DLL file, by selecting Make... from the File menu.

codedownload.gif (1765 bytes) Download project for this article here


Author: Michael Jones



Visual Basic | ASP | Web Scripting