我有一个 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
仍然有效!),但在最后一行我收到错误“需要对象”。我理解了tc
属于类型Variant/Object
,所以我认为 VBA 只是不知道如何处理它。有什么办法可以
- 告诉 VBA 这个类是什么样子的
- 实际上让它工作,以便调用函数
tc
在 VBA 中调用我的 .Net 库中的正确代码?
TestClass 类必须像 Utilities 类一样实现 - 它必须实现公共 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)