VBA中的COM对象ArrayList返回n个<无变量>项

3

我尝试使用C# ArrayList返回一组COM对象(在C#中开发),并在VBA(Excel 2007,.NET 4)中使用此COM对象列表。

我有3个C#函数,从Excel(VSTO项目)中调用这些函数。

    public ArrayList GetSimpleArray()
    {
        ArrayList arr = new ArrayList();
        arr.Add(3);
        arr.Add(2);
        return arr;
    }
    public ArrayList GetComplexArray()
    {
        ArrayList arr = new ArrayList();
        arr.Add(new Fund() { Id = "2" } );
        arr.Add(new Fund() { Id = "3" });
        return arr;
    }
    public IFund GetComplexObject()
    {
        return new Fund() { Id = "2" };
    }

定义了Fund和IFund:

[ComVisible(true)]
public interface IFund 
{
    string Id { get; set; }        
    string Name { get; set; }
}

[ComVisible(false)]
public sealed class Fund:IFund
{
    public string Id { get; set; }
    public string Name { get; set; }

    public Fund()
    {
    }

    public Fund(string id, string name)
    {
        this.Id     = id;            
        this.Name   = name;
    }
}

在Excel中我有:

Public Sub GetComObject()

  Call InitVSTOAddIn ' Initialise automationObject

  Dim complexObject
  Set complexObject = automationObject.GetComplexObject()

  Dim simpleArray
  Set simpleArray = automationObject.GetSimpleArray()

  Dim complexArray
  Set complexArray = automationObject.GetComplexArray()

End Sub

complexObject和simpleArray具有我正在寻找的值(complexObject是一个带有Id和Name的对象,simpleArray是一个包含2个元素“3”和“2”的ArrayList)。

问题在于complexArray。它是一个具有2个项目的ArrayList,但每个项目都是“无变量”(请参见附图)。

VBA Locals

你知道为什么吗?

在C#中是否有一种返回COM对象列表并在VBA中使用它们的方法?

这样做是好的实践还是在VBA中使用C#对象的更好方式?

谢谢您的帮助。


你尝试将复杂的ArrayList的ComVisible设置为true了吗? - Chris Gessler
GetComplexObject() 返回一个 (comvisible) IFund,而 GetComplexArray 返回的不是 comvisible 的 Fund 对象。为什么你把 Fund 设为了 comvisible(false)? - Eddy
我更喜欢只将接口IFund作为COM可见。当我返回complexObject时它可以工作。为了确保,我尝试将Fund设置为ComVisible,但仍然无法工作。 - Gutti
在大多数情况下,List<T>比ArrayList更可取。这是一个小建议,详见链接:https://dev59.com/RnRB5IYBdhLWcg3wFz8g - Amicable
1个回答

0

我找到了一种解决这个问题的方法,那就是创建一个包含属性 IFund[] ListFund 的 IListFund。

[ComVisible(true)]
public interface IListFund
{
    public IFund[] ListFund { get; set; }
}

然后我可以在Excel中拥有:

Public Sub GetComObject()

  Call InitVSTOAddIn ' Initialise automationObject '

  Dim complexObject As ComEqd.IListFund
  Dim complexArr() As ComEqd.IFund

  Set complexObject = automationObject.GetComplexObject()
  complexArr = complexArr.ListFund

End Sub

如果这个有效,请将其标记为正确答案,以便其他人知道。 - Scott Conover

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接