我有一个Excel VSTO COM加载项,可以在Excel VBA中成功加载引用。我可以交换基本类型(如字符串),但是我也可以在VBA中使用外接程序中的复杂类吗?
假设我在C#中有此类:
public class TestClass {
public string GetTextFunc() => "check";
public string TextProp => "doublecheck";
public int RollDice() => 4; // chosen by fair dice roll
}
...并且我的插件将此类的对象提供给Excel:
[ComVisible(true)]
public interface IUtilities {
string GetString();
TestClass GetTestClass();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Utilities: IUtilities {
public string GetString() => "Hello Excel";
public TestClass GetTestClass() => new TestClass();
}
因此,除该类外,所有内容都是默认的VSTO-tutorial-stuff。
现在,当我在Excel VBA块中(例如在“ ThisWorksheet”中)使用插件时,通过定义如下函数:
Sub TestAddin()
Dim addIn As COMAddIn
Dim automationObject As Object
Set addIn = Application.COMAddIns("MyExcelAddin")
Set automationObject = addIn.Object
ActiveSheet.Range("A1").Value2 = automationObject.GetString()
Dim tc
Set tc = automationObject.GetTestClass()
ActiveSheet.Range("A2").Value2 = tc.GetTextFunc()
End Sub
...然后按预期正确设置了A1,并且我可以一直调试到最后一行(因此获取对象tc
仍然有效!),但是在最后一行,我收到错误消息“ Object required”。我可以看到它tc
是type Variant/Object
,所以我认为VBA只是不知道该怎么做。有什么办法
tc
在VBA中调用函数可以在我的.Net库中调用正确的代码?必须与您的实用程序类一样实现TestClass类-它必须实现公共IDispatch派生的接口。
[ComVisible(true)]
public interface ITestClass {
string GetTextFunc();
string TextProp ();
int RollDice();
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class TestClass : ITestClass {
public string GetTextFunc() => "check";
public string TextProp => "doublecheck";
public int RollDice() => 4;
}
现在,VBA调用对以下方法具有类接口GetTextFunc
:
Dim tc
Set tc = automationObject.GetTestClass()
ActiveSheet.Range("A2").Value2 = tc.GetTextFunc()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句