Search code examples
vbaexceluser-defined-types

How to return array of user defined types, and then pass as an argument in VBA


I have a User Defined Type, Decision:

Public Type Decision
    choice As String
    cost As Double
End Type

I am trying to use an array of my UDTs to store the results of a dynamic program (choice and cost for a stage/state).

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

If I want to then pass the result of this function to a new function (to say, print the Table() in Excel, or do more work using the Table() result, how do I do this?

I am trying

Sub Main
    Dim x as variant

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

    Function2(x)
End Main

but am getting the following error: Compile Error

I have tried making x an array, but I get a "cannot assign to array" error. I have also tried making x a Decision, but that did not work either. The code is in a module.

Thanks!


Solution

  • So DPSolve shall return an array of Decisions. And x()shall also be an array of Decisions.

    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
    

    Works for me. Example:

    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
    

    To be clear with "Can't assign to an array". You can't assign an type and size dimensioned and filled array to another type and size dimensioned array. But you surely can assign an filled array to an type dimensioned but not size dimensioned array.

    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