4

I'm trying to write a function that would return an array of custom objects. Here is what I have so far:

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 that says:

only user-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound functions

My entire code is in a public module. How do I 'coerce' a function to return an array of custom objects?

2
  • Use a class module Commented Nov 26, 2017 at 16:30
  • As Ron said. Here is an example using Class and collection stackoverflow.com/questions/46049798/… Commented Nov 26, 2017 at 16:59

1 Answer 1

2

Set the return value of 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.