如何返回用户定义types的数组,然后在VBA中作为parameter passing

我有一个用户定义的types,决定:

Public Type Decision choice As String cost As Double End Type 

我正在尝试使用我的UDT的数组来存储dynamic程序的结果(舞台/状态的select和成本)。

 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 

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

我在尝试

 Sub Main Dim x as variant x = DPSolve(arg1, arg2, ...) Function2(x) End Main 

但是得到以下错误: 编译错误

我已经尝试使x数组,但我得到一个“不能分配给数组”的错误。 我也尝试过做出决定,但是这也不起作用。 代码在一个模块中。

谢谢!

所以DPSolve应该返回一个Decision数组。 而且x()也应该是Decision的一个数组。

 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 

用“不能分配给数组”来清除。 您不能将types和大小的维数和填充数组分配给其他types和大小的维数组。 但是你当然可以分配一个填充数组到一个尺寸的types但不是尺寸标注的数组。

 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 

错误意味着您不能将定义的types分配给变体。 所以你要么需要在variables上定义types

 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 choice As String Public cost As Double