如何返回用户定义类型的数组,然后在VBA中作为参数传递

如何返回用户定义类型的数组,然后在VBA中作为参数传递,vba,excel,user-defined-types,Vba,Excel,User Defined Types,我有一个用户定义的类型,决策: Public Type Decision choice As String cost As Double End Type Public choice As String Public cost As Double 我试图使用UDT数组来存储动态程序的结果(阶段/状态的选择和成本) 如果我想将这个函数的结果传递给一个新函数(也就是说,在Excel中打印Table(),或者使用Table()结果做更多的工作,我该怎么做 我正在努力 Sub Mai

我有一个用户定义的类型,决策:

Public Type Decision
    choice As String
    cost As Double
End Type
Public choice As String
Public cost As Double
我试图使用UDT数组来存储动态程序的结果(阶段/状态的选择和成本)

如果我想将这个函数的结果传递给一个新函数(也就是说,在Excel中打印Table(),或者使用Table()结果做更多的工作,我该怎么做

我正在努力

Sub Main
    Dim x as variant

    x = DPSolve(arg1, arg2, ...)

    Function2(x)
End Main
但是我得到了以下错误:

我曾尝试将x设置为数组,但出现“无法分配给数组”错误。我还尝试将x设置为决策,但也没有成功。代码位于模块中


谢谢!

因此
DPSolve
将返回一个
Decision
s数组。
x()
也将返回一个
Decision
s数组

Public Type Decision
    choice As String
    cost As Double
End Type

Public Function DPSolve(arg1, arg2) As Decision()
        Dim Table() As Decision
        ReDim Table(arg1, arg2 + 1)

        'do stuff that fills each Table().choice and Table().cost

        'return Table()
        DPSolve = Table()
End Function

Sub Main()
    Dim x() As Decision

    x = DPSolve(2, 2)

End Sub
适合我。例如:

Public Type Decision
    choice As String
    cost As Double
End Type

Public Function DPSolve(arg1, arg2) As Decision()
        Dim Table() As Decision
        ReDim Table(arg1, arg2 + 1)

        'do stuff that fills each Table().choice and Table().cost

        Table(1, 2).choice = "choice1,2"
        Table(1, 2).cost = 123.45

        'return Table()
        DPSolve = Table()
End Function

Sub Main()
    Dim x() As Decision

    x = DPSolve(2, 2)

    MsgBox x(1, 2).choice
    MsgBox x(1, 2).cost


End Sub
“无法分配给数组”一词很清楚。您不能将类型和大小标注的填充数组分配给另一个类型和大小标注的数组。但您肯定可以将填充数组分配给类型标注但大小标注的数组

Sub test()

 Dim arr1(3) As String
 Dim arr2() As String

 arr1(0) = "Value 0"
 arr1(1) = "Value 1"
 arr1(2) = "Value 2"
 arr1(3) = "Value 3"

 arr2 = arr1

 MsgBox Join(arr2, ", ")

End Sub

该错误意味着您无法将定义的类型分配给变量。 因此,您需要在变量上定义类型

Public Type Decision
    choice As String
    cost As Double
End Type

Public Sub DPSolve(source, arg1, arg2)
  ReDim source(arg1, arg2 + 1)
End Sub

Sub Main()
    Dim x() As Decision
    DPSolve x, 4, 4
End Sub
或者,如果确实要使用变体,则需要使用类:

Public Sub DPSolve(source, arg1, arg2)
  Dim i&, j&
  ReDim source(0 To arg1, 0 To arg2 + 1) As Decision
  For i = 0 To arg1
    For j = 0 To arg2 + 1
      Set source(i, j) = New Decision
    Next
  Next
End Sub

Sub Main()
    Dim x
    DPSolve x, 4, 4
End Sub
班级决定:

Public Type Decision
    choice As String
    cost As Double
End Type
Public choice As String
Public cost As Double

我一直不明白为什么MS不支持强制转换到VT_USERDEFINED的变体…我尝试了这个,但得到了一个“无法分配到数组”错误。我认为你不能在VBA中分配像a1()=a2()这样的数组。请参见确保你已经完全尝试了该代码?
公共函数DPSolve(arg1,arg2)As Decision()
注意
Decision()后面的括号
@Mark-
x=DPSolve(2,2)
,而不是
x()=DPSolve(2,2)
@AxelRichter将
DPSolve(arg1,arg2)作为决策()
包括括号,并且
x=DPSolve(2,2)
起作用。