vba 使用com-interop将数组从vba传递到c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2027758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass an array from vba to c# using com-interop
提问by Freddie
What is the proper way to pass an array of user defined classes from vba to .net (specifically c#) using com-interop?
使用 com-interop 将用户定义的类数组从 vba 传递到 .net(特别是 c#)的正确方法是什么?
Here's my c# code. If I call Method1 from vba it's failing with "Array or userdefined type expected" or "Function uses an automation type not supported in visual basic".
这是我的 C# 代码。如果我从 vba 调用 Method1,它会因“预期的数组或用户定义类型”或“函数使用 Visual Basic 中不支持的自动化类型”而失败。
public class MyClass
{
public Method1(UserDefinedClass[] Parameters) { ... }
public Method2(Object Parameters) { ... }
}
I've read a bit about the MarshallAsAttribute class. Could this be the missing piece in the c# code?
我已经阅读了一些关于 MarshallAsAttribute 类的内容。这可能是 c# 代码中缺少的部分吗?
Here's the vba code I'm using:
这是我正在使用的 vba 代码:
Dim udt As New UserDefinedClass
Dim myArray()
myArray(1) = udt
myClass.Method1(myArray)
myClass.Method2(myArray)
回答by Joe
IIRC you have to pass arrays by reference.
IIRC 你必须通过引用传递数组。
Try declaring your method as
尝试将您的方法声明为
public class MyClass
{
public void Method1([In] ref UserDefinedClass[] Parameters) { ... }
...
}
If you don't want to pollute your class with ref parameters for .NET clients, you can define a ComVisible interface to be used by COM clients, and implement it explicitly thus:
如果您不想使用 .NET 客户端的 ref 参数污染您的类,您可以定义一个 ComVisible 接口以供 COM 客户端使用,并显式实现它:
[ComVisible(true)]
public interface IMyClass
{
void Method1([In] ref UserDefinedClass[] Parameters) { ... }
...
}
public class MyClass : IMyClass
{
void IMyClass.Method1(ref UserDefinedClass[] Parameters)
{
this.Method1(Parameters);
}
public Method1(UserDefinedClass[] Parameters)
{
...
}
}
** In response to comment ** If you want to expose a collection instead of an array to VBA, you just need to expose an enumerator, and any other methods you want the VBA code to be able to call (e.g. Add, Remove, Insert, Clear, ...). E.g.
** 回应评论 ** 如果您想向 VBA 公开一个集合而不是一个数组,您只需要公开一个枚举器,以及您希望 VBA 代码能够调用的任何其他方法(例如添加、删除、插入,清除,...)。例如
[ComVisible]
public interface IUserDefinedClassCollection
{
IEnumerator GetEnumerator();
int Count { get; };
IUserDefinedClass this[int index] { get; }
int Add(IUserDefinedClass item);
// etc, other methods like Remove, Clear, ...
}
You can then use it as usual in VBA:
然后你可以像往常一样在 VBA 中使用它:
Dim objUserDefinedClasses As UserDefinedClassCollection
...
objUserDefinedClasses.Add objUserDefinedClass
...
For nIndex = 0 To objUserDefinedClasses.Count
Next nIndex