How to return an array of user objects?

I am trying to write a function that returns an array of user objects. Here is what I still have:

Option Explicit

Public Type Node
     mValue As Integer
     mTo() As Integer
End Type

Function FillData()
    Dim a As Node
    Dim b As Node
    Dim c As Node
    Dim nody() As Node

    a.mValue = 1
    ReDim a.mTo(0 To 1)
    a.mTo(0) = 2

    b.mValue = 2
    ReDim b.mTo(0 To 1)
    b.mTo(0) = 3

    c.mValue = 3
    ReDim c.mTo(0 To 1)
    c.mTo(0) = 1

    ReDim nody(0 To 2)
    nody(0) = a
    nody(1) = b
    nody(2) = c

    FillData = nody
End Function

Sub test()
    Dim data() As Node
    data = FillData()
End Sub

The problem is that when I try to run it (test sub), I get a compilation error in FillData = nody, which reads:

only user types defined in public object modules can be forcibly applied to or from a variant or passed to functions with late bounds

All my code is in an open module. How can I β€œforce” a function to return an array of user objects?

+4
source share
1 answer

Set the return value of the function.

Option Explicit

Public Type Node
     mValue As Integer
     mTo() As Integer
End Type

Function FillData() As Node()
    Dim a As Node
    Dim b As Node
    Dim c As Node
    Dim nody() As Node

    a.mValue = 1
    ReDim a.mTo(0 To 1)
    a.mTo(0) = 2

    b.mValue = 2
    ReDim b.mTo(0 To 1)
    b.mTo(0) = 3

    c.mValue = 3
    ReDim c.mTo(0 To 1)
    c.mTo(0) = 1

    ReDim nody(0 To 2)
    nody(0) = a
    nody(1) = b
    nody(2) = c

    FillData = nody
End Function

Sub test()
    Dim data() As Node
    data = FillData()
End Sub
+2
source

Source: https://habr.com/ru/post/1689863/


All Articles