How do I use a .NET class in VBA? Syntax help!

Posted by Jordan S on Stack Overflow See other posts from Stack Overflow or by Jordan S
Published on 2010-04-01T12:33:08Z Indexed on 2010/04/01 13:33 UTC
Read the original article Hit count: 546

Filed under:
|
|
|
|

ok I have couple of .NET classes that I want to use in VBA. So I must register them through COM and all that. I think I have the COM registration figured out (finally) but now I need help with the syntax of how to create the objects. Here is some pseudo code showing what I am trying to do.

EDIT: Changed Attached Objects to return an ArrayList instead of a List

The .NET classes look like this...

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)
    {

    }

}

OK, so this is what I would like to do in VBA (demonstrated in C#) but I don't know how...

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
        }
    }
}

One thing to note is that RandomObject does not have a public default constructor. So I can not create an instance of it like Dim x As New RandomObject. MSDN says that you can not instantiate an object that doesn't have a default constructor through COM but you can still use the object type if it is returned by another method... 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.

Added: Here is my attempt in VB:

Dim count As Integer
count = 0
Dim myObj As New ResourceManagment
For Each RandomObject In myObj.AttachedObjects
    count = count + 1
Next RandomObject

© Stack Overflow or respective owner

Related posts about vba

Related posts about .NET