Search code examples
arraysvbaparameter-passingsubroutinecustom-data-type

VBA: passing variables to sub() with custom type


I am playing with calling a sub() but keep getting "User-defined type not defined" error. Unable to figure out after trying different ways of declaring variables as array. Would appreciate any guidance on this:

Public Type Whatever
    ppp As String
    qqq As Long
    rrr As Single
End Type




Sub isthisworking()
 Dim thisis() As Whatever
 Dim i As Long
 Dim athing As Long

 For i = 0 To 5
    With thisis(i)
        .ppp = i & "p"
        .qqq = i * 2
        .rrr = i ^ 3
    End With

 athing = 20

 beingcalled thisis(), athing

End Sub



Public Sub beingcalled(ByRef thisis() As Whatever, athing As Long)

 Dim cycles As Long

 cycles = UBound(thisis)

 For i = 0 To cycles - 1
    With thisis(i)
        Debug.Print i & ": " & .ppp & "," & .qqq & "," & .rrr
    End With
 Next


End Sub

Solution

  • Your For i = 0 To 5 is missing the closing Next i statement.

    You need to Redim the size of your thisis() array:

    ReDim thisis(o To 5)
    

    the whole "isthisworking" Sub:

    Sub isthisworking()
    
    Dim thisis() As Whatever
    Dim i As Long
    Dim athing As Long
    
    ReDim thisis(o To 5)
    
    For i = 0 To 5
       With thisis(i)
           .ppp = i & "p"
           .qqq = i * 2
           .rrr = i ^ 3
       End With
    Next i
    
    athing = 20
    
    beingcalled thisis(), athing    
    ' you can pass also thisis (without the brackets) gives the same result
    
    End Sub