Microsoft Visual Studio Tools for the Microsoft Office system (version 3.0)
Walkthrough: Calling Code in an Application-Level Add-in from VBA

Updated: September 2008

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Application-level projects

Microsoft Office version

  • 2007 Microsoft Office system

  • Microsoft Office 2003

For more information, see Features Available by Application and Project Type.

This walkthrough demonstrates how to expose an object in an application-level add-in to other Microsoft Office solutions, including Visual Basic for Applications (VBA) and COM add-ins.

Although this walkthrough uses Excel specifically, the concepts demonstrated by the walkthrough are applicable to any add-in project provided by Visual Studio Tools for Office. 

This walkthrough illustrates the following tasks:

  • Defining a class that can be exposed to other Office solutions.

  • Exposing the class to other Office solutions.

  • Calling a method of the class from VBA code.

NoteNote:

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio Tools for Office (an optional component of Visual Studio 2008 Professional and Visual Studio Team System).

  • Microsoft Office Excel 2007.

    NoteNote:

    You can also perform this walkthrough using Microsoft Office Excel 2003. However, some of the instructions assume you are using the Ribbon in Excel 2007.

Visual Studio Tools for Office is installed by default with the listed versions of Visual Studio. To check whether it is installed, see Installing Visual Studio Tools for Office.

link to video For a video version of this topic, see Video How to: Calling Code in an Application-Level Add-in from VBA.

Creating the Add-in Project

The first step is to create an add-in project for Excel.

To create a new project

  • Create an Excel Add-in project with the name ExcelImportData, using the Excel Add-in project template for the 2007 Microsoft Office system. For more information, see How to: Create Visual Studio Tools for Office Projects.

    Visual Studio opens the ThisAddIn.cs or ThisAddIn.vb code file and adds the ExcelImportData project to Solution Explorer.

Defining a Class That You Can Expose to Other Office Solutions

The purpose of this walkthrough is to call into the ImportData method of a class named AddInUtilities in your add-in from VBA code. This method writes a string into cell A1 of the active worksheet.

To expose the AddInUtilities class to other Office solutions, you must make the class public and visible to COM. You must also expose the IDispatch interface in the class. The code in the following procedure demonstrates one way to meet these requirements. For more information, see Calling Code in Application-Level Add-ins from Other Solutions.

To define a class that you can expose to other Office solutions

  1. On the Project menu, click Add Class.

  2. In the Add New Item dialog box, change the name of the new class to AddInUtilities, and click Add.

    The AddInUtilities.cs or AddInUtilities.vb file opens in the Code Editor.

  3. Add the following statements to the top of the file.

    Visual Basic
    Imports System.Data
    Imports System.Runtime.InteropServices
    Imports Excel = Microsoft.Office.Interop.Excel
    
    C#
    using System.Data;
    using System.Runtime.InteropServices;
    using Excel = Microsoft.Office.Interop.Excel;
    
  4. Replace the empty AddInUtilities class declaration with the following code.

    This code makes the AddInUtilities class visible to COM, and it adds the ImportData method to the class. To expose the IDispatch interface, the AddInUtilities class also has the ClassInterfaceAttribute attribute, and it implements an interface that is visible to COM.

    Visual Basic
    <ComVisible(True)> _
    Public Interface IAddInUtilities
        Sub ImportData()
    End Interface
    
    <ComVisible(True)> _
    <ClassInterface(ClassInterfaceType.None)> _
    Public Class AddInUtilities
        Implements IAddInUtilities
    
        ' This method tries to write a string to cell A1 in the active worksheet.
        Public Sub ImportData() Implements IAddInUtilities.ImportData
    
            Dim activeWorksheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet
    
            If activeWorksheet IsNot Nothing Then
                Dim range1 As Excel.Range = activeWorksheet.Range("A1")
                range1.Value2 = "This is my data"
            End If
        End Sub
    End Class
    
    C#
    [ComVisible(true)]
    public interface IAddInUtilities
    {
        void ImportData();
    }
    
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class AddInUtilities : IAddInUtilities
    {
        // This method tries to write a string to cell A1 in the active worksheet.
        public void ImportData()
        {
            Excel.Worksheet activeWorksheet = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;
    
            if (activeWorksheet != null)
            {
                Excel.Range range1 = activeWorksheet.get_Range("A1", System.Type.Missing);
                range1.Value2 = "This is my data";
            }
        }
    }
    
Exposing the Class to Other Office Solutions

To expose the AddInUtilities class to other Office solutions, override the RequestComAddInAutomationService method in the ThisAddIn class. In your override, return an instance of the AddInUtilities class.

To expose the AddInUtilities class to other Office Solutions

  1. In Solution Explorer, expand Excel.

  2. Right-click ThisAddIn.cs or ThisAddIn.vb, and then click View Code.

  3. Add the following code to the ThisAddIn class.

    Visual Basic
    Private utilities As AddInUtilities
    
    Protected Overrides Function RequestComAddInAutomationService() As Object
        If utilities Is Nothing Then
            utilities = New AddInUtilities()
        End If
        Return utilities
    End Function
    
    C#
    private AddInUtilities utilities;
    
    protected override object RequestComAddInAutomationService()
    {
        if (utilities == null)
            utilities = new AddInUtilities();
    
        return utilities;
    }
    
  4. On the Build menu, click Build Solution.

    Verify that the solution builds without errors.

Testing the Add-In

You can call into the AddInUtilities class from several different types of Office solutions. In this walkthrough, you will use VBA code in an Excel workbook. For more information about the other types of Office solutions you can also use, see Calling Code in Application-Level Add-ins from Other Solutions.

To test your add-in

  1. Press F5 to run your project.

  2. In Excel, save the active workbook as an Excel Macro-Enabled Workbook (*.xlsm). Save it in a convenient location, such as the desktop.

  3. On the Ribbon, click the Developer tab.

    NoteNote:

    If the Developer tab is not visible, you must first show it. For more information, see How to: Show the Developer Tab on the Ribbon.

  4. In the Code group, click Visual Basic.

    The Visual Basic Editor opens.

  5. In the Project window, double-click ThisWorkbook.

    The code file for the ThisWorkbook object opens.

  6. Add the following VBA code to the code file. This code first gets a COMAddIn object that represents the ExcelImportData add-in. Then, the code uses the Object property of the COMAddIn object to call the ImportData method.

    Sub CallVSTOMethod()
        Dim addIn As COMAddIn
        Dim automationObject As Object
        Set addIn = Application.COMAddIns("ExcelImportData")
        Set automationObject = addIn.Object
        automationObject.ImportData
    End Sub
    
  7. Press F5.

  8. Verify that a new Imported Data sheet has been added to the workbook. Also verify that cell A1 contains the string This is my data.

  9. Exit Excel.

Next Steps

You can learn more about programming add-ins from these topics:

See Also

Tasks

Concepts

Change History

Date

History

Reason

September 2008

Simplified code example.

Customer feedback.

Tags :


Community Content

dayst5
Error in Excel 2003

When I try to recreate this project as an Excel 2003 Add-in, I get the following error:

The name 'Globals' does not exist in the current context

In the following line of code:

Excel.Workbook activeWorkbook =  Globals.Application.ActiveWorkbook;
Tags :

Martin Wills
Re: Error in Excel 2003

Q1 - When you created your project, did you choose Excel 2003 Add-in from the list of Visual Studio Installed Templates?

If not, there's your reason.

Q2 - If you did, do you have a file called ThisAddIn.cs with the line publicpartialclassThisAddIn?

Q3 - If you right-click on ThisAddIn and choose Go toDefinition, do you get offered 2 choices - the second being in a file ThisAddIn.Designer.cs?

If you click on that choice and thereby open the file, check the following.

(a) Q4 - Is the namespace in that file the same as that in your file referencing Globals.Application.ActiveWorkbook?
(b) Q5 - In that file, is there a line internalsealedpartialclassGlobals {?

The answers to all 5 questions should be yes but in that case you wouldn't get the error you report.

Any No answers should help you identify the problem.

Tags :

Mehran Nikoo [MSFT]
Wrong Data Type In Sample VB.NET Code

Under section “Defining a Class That You Can Expose to Other Office Solutions”, in the VB.NET code, the data type should be Excel.Worksheet not Excel.Workbook. The C# code is fine.

So this line:

Dim activeWorksheet AsExcel.Workbook = Globals.ThisAddIn.Application.ActiveSheet


Should be changed to:

Dim activeWorksheet AsExcel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet
Tags :

McLean Schofield - MSFT
RE: Wrong Data Type In Sample VB.NET Code
Thank you for bringing this issue to our attention, and I apologize that issue slipped into the documentation. The Visual Basic code example has been fixed, and the fix should appear in the next online refresh of the documentation.

davidm999
Excel Pivot table

Great tutorial.

Are there any examples out there of using the same technique of "Calling Code in an Application-Level Add-in from VBA" but create a DataSet object from a query to say SQLServer and add the Dataset (normally a PivotCache object in VBA) and then passing this pivotcache back to the calling VBA function - with all of the normal pivot properties available to be configured.

Within the class (ideally C# in my case) , the PivotCache has a equivalent RecordSet property in VBA that a ADODB.RecordSet can be assigned to. In VSTO can a DataSet object be assigned to an Excel.PivotCache object? If anyone could offer some guidance here that would be great.

Sub CallVSTOMethod()
Dim addIn As COMAddIn
Dim automationObject As PivotCache
Dim pt as PivotTable
Set addIn = Application.COMAddIns("ExcelImportData")
Set automationObject = addIn.Object
automationObject.GetPivotCache

'carry out normal pivot manip
Set pt = wsSheet.PivotTables.Add(PivotCache:=automationObject , TableDestination:=wsSheet.Range("B5"), TableName:="myPivot")
'etc

End Sub





JimBassett
Cannot use CreateObject
When this type addin is created using VB6 one can use CreateObject to create an instance of the addin object. CreateObject does not work with VSTO created addins.
Tags :

jleoneBGSU
VBA Intellisense
Is there any way to get excel's VBA Intellisense to recognize the functions in the AddInUtilities Class? I would like to do this so when I distribute my addIn people will be able to create the COMaddIn and then use the functions as they please.
Tags :

Page view tracker