如何在VBA中使用.NET类?语法帮助!

PIC*_*ain 6 .net com vba instantiation

好吧,我想在VBA中使用几个.NET类.所以我必须通过COM注册它们.我想我已经找到了COM注册(最后),但现在我需要有关如何创建对象的语法的帮助.这是一些伪代码,显示了我想要做的事情.

编辑:更改附加对象以返回ArrayList而不是List

.NET类看起来像这样......

public class ResourceManagment
{
    public ResourceManagment()
    {
        // Default Constructor
    }

    public static List<RandomObject> AttachedObjects()
    {
        ArrayList list = new ArrayList();
        return list;
    }
}

public class RandomObject
{
    // 
    public RandomObject(int someParam)
    {

    }

}
Run Code Online (Sandbox Code Playgroud)

好的,这就是我想在VBA中做的事情(用C#演示),但我不知道怎么做......

public class VBAClass
{
    public void main()
    {
        ArrayList myList = ResourceManagment.AttachedObjects();
        foreach(RandomObject x in myList)
        {
            // Do something with RandomObject x like list them in a Combobox
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

需要注意的一点是RandomObject没有公共默认构造函数.所以我无法创建它的实例Dim x As New RandomObject.MSDN说你不能通过COM实例化一个没有默认构造函数的对象,但是如果它被另一个方法返回,你仍然可以使用它.Types must have a public default constructor to be instantiated through COM. Managed, public types are visible to COM. However, without a public default constructor (a constructor without arguments), COM clients cannot create an instance of the type. COM clients can still use the type if the type is instantiated in another way and the instance is returned to the COM client. You may include overloaded constructors that accept varying arguments for these types. However, constructors that accept arguments may only be called from managed (.NET) code.

补充:这是我在VB中的尝试:

Dim count As Integer
count = 0
Dim myObj As New ResourceManagment
For Each RandomObject In myObj.AttachedObjects
    count = count + 1
Next RandomObject
Run Code Online (Sandbox Code Playgroud)

Fyo*_*kin 1

你的问题是该AttachedObjects()方法是静态的。COM 不能执行静态方法。在 COM 中,您可以执行的唯一“静态”操作是“实例化类”。

因此,为了AttachedObjects从 VBA 调用该方法,只需将其设置为非静态(即删除static其定义中的关键字)。除此之外,该方法可能会保持原样。而且你的 VBA 代码看起来也不错 - 一旦你修改了方法就应该可以工作。

以防万一它不起作用,这是下一个问题:您到底会遇到什么错误,在什么时候出现?