【发布时间】:2011-06-28 17:02:05
【问题描述】:
是否可以使用 COM 将自定义对象(如 MyClass[])从 C# 传递到 VBA?
如果不是,哪个是最好的解决方案?
【问题讨论】:
-
搜索到了stackoverflow.com/questions/375457/…,这可能很有趣。
-
只要你把它设为 ComVisible,就可以。
是否可以使用 COM 将自定义对象(如 MyClass[])从 C# 传递到 VBA?
如果不是,哪个是最好的解决方案?
【问题讨论】:
我假设您正在谈论 Excel VBA 到 C# ...
这是一个最小的 C# 类,在一个默认名称为 ClassLibrary1 的项目中:
using System;
using System.Runtime.InteropServices;
namespace Tester
{
[ClassInterface(ClassInterfaceType.AutoDual)]
public class TestClass
{
public double D { get; set; } // simple property to get, set a double
public string S { get; set; } // simple property to get, set a string
}
}
这里是 VBA 来试试这个课程:
Private Sub foo()
Dim X As New ClassLibrary1.TestClass
X.S = "Hello"
Debug.Print X.S ' prints "hello"
X.D = 12
Debug.Print X.D ' prints a 12
End Sub
要完成这项工作,您还需要做一些额外的事情:
(1) in C# Project...Properties...Build ==> check "Register for COM interop
(2) in C# Project...Properties...Application...Assembly Information ==>
check "Make assembly COM-visible"
(3) in VBA ... Tools ... References, browse to the C# bin output directory and select the "*.tlb" file
注意:此方案可能会失败,具体取决于您添加到类中的内容 - 我认为 VBA 不会“看到”静态类或除了默认构造函数之外的类。您也不能将 VB 集合映射到 .NET 集合,但您将能够来回传递基本类型(double、long)和基本类型的数组。此外 - 使用的“Autodual”选项是一种公开方法的廉价方式......易于上手但效率较低并且公开了所有公共方法。更好的做法(但更多的工作)是设置您自己的接口。如果您扩展此 TestClass 的成员以包含您定义的其他类的实例,并且如果您同样通过 AutoDual 或通过手动编码的接口公开这些类方法,那么这些类及其(非重载)方法同样是可见的在 VBA 中(使用 Intellisense)。
希望这会有所帮助。
【讨论】: