在宏中调用Excel加载项功能

用户5590

我正在为Excel 2013开发外接程序,并在Excel外接程序中创建了一个功能,如下所示

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

我已经使用下面的代码来调用该函数,但是会引发错误。

Application.Run(ExcelReturnString)

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

火腿骨

这是最直接的事情,但这是完成任务的方式。我将尽可能地明确,因为在尝试进行此操作的前两三次中,我错过了很多。

首先,在创建宿主类时,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";
        }
    }
}

然后,在与项目中的“ 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
    }
}

现在,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年的时间来解决这个问题,而我不会。实际上,将其上的Rosetta石头归功于MSDN:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章