在宏中调用 Excel 加载项函数

Call Excel Add-In function in macro

我正在为 Excel 2013 开发插件,我在 Excel 插件中创建了一个函数,如下所示

  public string ExcelReturnString()
    {
        return "This is the string: hi";
    }

我使用下面的代码调用函数,但它抛出错误。

Application.Run(ExcelReturnString)

如何在宏中调用插件功能?

您的代码似乎是 java。

例如,

Excel 使用 Visual basic。

Function excelreturnstring()
    excelreturnstring = "this is the string: hi"
End function

除了上面 DaveMac 的注释外,在调用另一个例程时还请记住几点:

如果您从与该例程位于同一 workbook/addin 中的例程调用宏,则不必使用 Application.Run。您可以使用它的名称来调用它:

MyMacro

如果您要调用位于不同工作簿中的宏,那么您确实需要使用 Application.Run,但您还需要使用宏所在的工作簿名称,否则 VBA 不知道应该在哪里寻找宏:

Application.Run "'My Fancy Spreadsheet.xlsm!'MyMacro"

这离直截了当最远,但这就是您完成任务的方式。我将尽可能明确,因为我尝试这样做的前两三次,我错过了很多。

首先,当您创建承载 ExcelReturnString() 的 class 时,您需要使用具有以下属性的接口来装饰 class,然后还标记每个属性你想公开的方法。为了这个例子,我制作了加载项 class "TestExcelAddIn":

using System.Data;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace TestExcelAddIn
{
    [ComVisible(true)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IStringGetter
    {
        string ExcelReturnString();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class StringGetter : IStringGetter
    {
        public string ExcelReturnString()
        {
            return "This is the string: hi";
        }
    }
}

然后,在与项目中的 "Excel" 关联的主要 class 中,您必须按以下方式覆盖 RequestComAddInAutomationService。再一次,我把所有东西都包括在内,所以你知道哪个 class 是哪个(我第一次阅读时没有)。

namespace TestExcelAddIn
{
    public partial class ExcelTest
    {
        private StringGetter myAddIn;

        protected override object RequestComAddInAutomationService()
        {
            if (myAddIn == null)
                myAddIn = new StringGetter();

            return myAddIn;
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code
        #endregion
    }
}

现在 VBA 已准备好按以下方式使用此方法:

Sub Test()

    Dim addin As Office.COMAddIn
    Dim automationObject As Object
    Dim returnString As String

    Set addin = Application.COMAddIns("TestExcelAddIn")
    Set automationObject = addin.Object

    returnString = automationObject.ExcelReturnString

End Sub

你本可以给我 100 年的时间来解决这个问题,但我不会。实际上将罗塞塔石碑归功于 MSDN:

https://msdn.microsoft.com/en-us/library/bb608621.aspx?f=255&MSPPError=-2147217396