简体   繁体   English

使用com-interop将数组从vba传递给c#

[英]Pass an array from vba to c# using com-interop

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. 这是我的c#代码。 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". 如果我从vba调用Method1,它将失败“预期的数组或用户定义类型”或“函数使用visual basic中不支持的自动化类型”。

public class MyClass 
{
    public Method1(UserDefinedClass[] Parameters) { ... }
    public Method2(Object Parameters) { ... }
}

I've read a bit about the MarshallAsAttribute class. 我已经阅读了一些关于MarshallAsAttribute类的内容。 Could this be the missing piece in the c# code? 这可能是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)

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参数污染您的类,您可以定义COM客户端使用的ComVisible接口,并明确地实现它:

[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 (eg Add, Remove, Insert, Clear, ...). **响应注释**如果要将集合而不是数组公开给VBA,您只需要公开一个枚举器,以及您希望VBA代码能够调用的任何其他方法(例如,添加,删除,插入,清除,...)。 Eg 例如

[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM