Array contains subarray which UDT inside

Viewed 59

I am trying to create an array which with UDTs subarary inside, and the code as below, But run with the error, "Only user-defined types defined in public object modules can be coerced to or from a variant or passed to late-bound functions". if anyone has a suggestion?

Option Explicit
Type udtA
    A As Integer
    B As Integer
    C As Integer
End Type
Sub Main()
    test
End Sub

Function test()
    Dim A() As Variant
    Dim B() As udtA, intRun As Integer
    Dim udtARun As udtA
    
    ReDim A(0)
    ReDim B(2)
    
    intRun = 1
    Do While intRun <= UBound(B) + 1
        With udtARun
            .A = 1 * intRun
            .B = 100 * intRun
            .C = 10000 * intRun
        End With
        B(intRun - 1) = udtARun
        intRun = intRun + 1
    Loop
    
    A(0) = B
    
End Function
2 Answers

I'm not strictly sure where yours went wrong...
This worked for me, but there are lots of things I've done differently.
For example I treated the udtA array as an array the entire way through.

As I'm not really sure what your end goal is with this, I'm not sure I can give you much more but I hope this working start helps out and you can slowly modify it untill it fits your needs.

Option Explicit

Type udtA
    A As Integer
    B As Integer
    C As Integer
End Type
Sub TestType()
    
    Dim I As Integer
    Dim tArray(1 To 5) As udtA
    
    For I = 1 To 5
        With tArray(I)
            .A = I * 1
            .B = I * 10
            .C = I * 100
        End With
    Next I
    
    Debug.Print tArray(1).A
    Debug.Print tArray(2).B
    Debug.Print tArray(3).C
    Debug.Print tArray(4).B
    Debug.Print tArray(5).A
    
End Sub

' Output:
'
' 1 
' 20 
' 300 
' 40 
' 5 

What this error message refers to as "public object modules" can be rather misleading to many programmers. As it turns out a "public object module" means a class that has been defined inside an ActiveX project (either EXE or DLL).

Now as to WHY only user-defined types declared in an ActiveX class can be coerced to and from a variant, remains a total mystery as I couldn't find an explanation anywhere.

You can solve this problem in two ways:

  1. Make a new ActiveX DLL project with a public class and put your UDT in there.

  2. Replace your UDT with a regular class that exposes the A, B, C as public properties.

Either way should work just fine so it's up to you which one you feel is more appropriate to your needs.

Related