gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:35:25 25 4
gpt4 key购买 nike

我正在尝试编写一个返回自定义对象数组的函数。这是我到目前为止所拥有的:

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

问题是,当我尝试运行它(测试子)时,我在 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

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

最佳答案

设置函数的返回值。

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

关于vba - 如何返回自定义对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com