Freigeben über


Walkthrough: Call code in a VSTO Add-in from VBA

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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

Applies to: The information in this topic applies to VSTO Add-in projects. For more information, see Features available by Office application and project type.

Although this walkthrough uses Excel specifically, the concepts demonstrated by the walkthrough are applicable to any VSTO Add-in project template provided by Visual Studio.

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.

    Note

    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 Personalize the IDE.

Prerequisites

You need the following components to complete this walkthrough:

Create the VSTO Add-in project

The first step is to create a VSTO Add-in project for Excel.

To create a new project

  1. Create an Excel VSTO Add-in project with the name ExcelImportData, using the Excel VSTO Add-in project template. For more information, see How to: Create Office Projects in Visual Studio.

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

Define 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 VSTO 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 VSTO Add-ins from Other Office 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 directives to the top of the file.

    using System.Data;
    using System.Runtime.InteropServices;
    using Excel = Microsoft.Office.Interop.Excel;
    
    Imports System.Data
    Imports System.Runtime.InteropServices
    Imports Excel = Microsoft.Office.Interop.Excel
    
  4. Replace the AddInUtilities class with the following code.

    [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";
            }
        }
    }
    
    <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
    

    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.

Expose 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.

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

    Verify that the solution builds without errors.

Test the VSTO 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 Call code in VSTO Add-ins from other Office solutions.

To test your VSTO 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.

    Note

    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 VSTO 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 VSTO Add-ins from these topics:

See also