在宏中调用Excel加载项功能

Use*_*590 3 c# excel vba excel-vba excel-addins

我正在开发Excel 2013的加载项,我在Excel加载项中创建了一个函数,如下所示

  public string ExcelReturnString()
    {
        return "This is the string: hi";
    }
Run Code Online (Sandbox Code Playgroud)

我使用下面的代码来调用函数,但它会抛出一个错误.

Application.Run(ExcelReturnString)
Run Code Online (Sandbox Code Playgroud)

如何在宏中调用外接功能?

Ham*_*one 7

这是关于直接前进的最远的事情,但这就是你完成任务的方式.我会尽可能地明确,因为前两次或三次我试图这样做,我错过了很多.

首先,当您创建托管的类时ExcelReturnString(),您需要使用具有以下属性的接口来装饰该类,然后还标记要公开的每个方法的属性.为了这个例子,我创建了加载类"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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在主类中,与项目中的"Excel"关联,您必须以RequestComAddInAutomationService下列方式覆盖.再一次,我包括了所有内容,所以你知道哪个类是哪个(我第一次阅读时没有).

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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在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
Run Code Online (Sandbox Code Playgroud)

你可以给我100年的时间来解决这个问题,但我不会.实际上,信用MSDN上的Rosetta石头:

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

  • 感谢哈伯恩的回复。这对我帮助很大。 (2认同)