returning an array of user-defined types from a function

Hello,

I'm relatively new to vba (and vb in general), so I appologise in advance if this is a dumb quesion.

I have a function which I want to return an array of user-define types from. I am getting this compile error, however: "Only user-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound functions."

This is my code:

Type
field1 As String
field2 As Integer
...
End Type

...

Function GetArray()
...
Dim arr() As MyType
ReDim arr(Selection.Rows.Count) As MyType

i = 0
For Each Row In Selection.Rows
Dim curr_type As MyType
curr_type.field1 = ...
curr_type.field2 = ...

arr(i) = curr_type
i = i + 1
Next

GetArray = arr
End Function

The error is on the last line, where I try to assign my array to the function value. Any help would be appreciated.

Thanks,
Gabe



Answer this question

returning an array of user-defined types from a function

  • Elham Sarikhani

    Function GetArray()

    should be replaced with:

    Function GetArray() As MyType

    Otherwise, the compiler assumes GetArray() returns a Variant, and tries to cast your MyType object to a Variant.



  • returning an array of user-defined types from a function