我希望能够从Excel VBA宏调用VSTO加载项中的函数。为了测试该原理,我具有以下C#代码。

namespace ExcelAddIn1
{
    [ComVisible(true)]
    public interface IThisAddIn
    {
        String GetText();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public partial class ThisAddIn : IThisAddIn
    {
        public String GetText()
        {
            return "Now is the winter of dicontent made glorius summer by this son of York";
        }
    }
}


我有以下VBA脚本

Public Sub RunTest()
    Dim txt As String
    Dim AddInList As Object
    Dim ExcelAddIn1 As COMAddIn
    Dim ThisAddIn As Object

    Set ExcelAddIn1 = Application.COMAddIns("ExcelAddIn1")

    txt = ExcelAddIn1.Object.GetText()
    Sheets(1).Cells(2, 1).Value = txt
End Sub


ExcelAddIn1.Object =无

微软在https://docs.microsoft.com/en-gb/visualstudio/vsto/walkthrough-calling-code-in-a-vsto-add-in-from-vba的演练似乎有些混乱。

我想我可能需要添加RequestComAddInAutomationService,但是它不能像本演练中所述那样工作。当我尝试在RequestComAddInAutomationService中实例化我的类的实例时,我得到的错误基本上是告诉我需要提供一个ApplicationFactory和IServiceProvider作为参数。

private ThisAddIn utilities;

protected override object RequestComAddInAutomationService()
{
    if (utilities == null)
       utilities = new ThisAddIn();

    return utilities;
}

最佳答案

IThisAddIn派生的类必须与主vsto类不同(例如在Microsoft示例中),因此只需将代码替换为:

  [ComVisible(true)]
    public interface IComAddIn
    {
        String GetText();
    }

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public  class AddInUtilities : IComAddIn
    {
        public String GetText()
        {
            return "Now is the winter of dicontent made glorius summer by this son of York";
        }
    }


在vsto中:

    public partial class ThisAddIn
    {
        private AddInUtilities utilities;

        protected override object RequestComAddInAutomationService()
        {
            if (utilities == null)
                utilities = new AddInUtilities();

            return utilities;
        }
  ....


同样,当您在VBA中调用Application.COMAddIns时,请确保作为参数提供的字符串与vsto项目的AssemblyTitle相对应。

PS没有必要“注册互操作”。

关于c# - 在VSTO office插件中创建可调用函数-COMAddIns.Object始终为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51909804/

10-13 06:38