如何返回自定义对象数组?

时间:2022-02-23 18:53:42

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:

问题是,当我尝试运行它(测试子)时,我在FillData = nody中得到一个编译错误:

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?

我的整个代码都在公共模块中。我如何'强制'函数返回一组自定义对象?

1 个解决方案

#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

#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