Search code examples
arraysvbams-accessvariant

Inserting in multidimensional variant array VBA MS Access


I'm trying to insert data to a 2 dimensional variant array in VBA based on a tutorial I found on google.

This is my code:

    Dim sampleVariant As Variant
    ReDim sampleVariant(3, 3)

    For sample = 0 To UBound(sampleVariant, 1)
        For information_e = 0 To UBound(sampleVariant, 2)
            sampleVariant(sample, information_e) = "Name ~row:" & sample & " ~column:" & information_e
        Next
    Next

The result is

Name ~row:1 ~column:1,Name ~row:1 ~column:2,Name ~row:1 ~column:3
Name ~row:2 ~column:1,Name ~row:2 ~column:2,Name ~row:2 ~column:3
Name ~row:3 ~column:1,Name ~row:3 ~column:2,Name ~row:3 ~column:3

How can I make it like

Name ~row:1 ~column:1,Age ~row:1 ~column:2,Address ~row:1 ~column:3
Name ~row:2 ~column:1,Age ~row:2 ~column:2,Address ~row:2 ~column:3
Name ~row:3 ~column:1,Age ~row:3 ~column:2,Address ~row:3 ~column:3

Solution

  • I think the best way to understand this is to actually see how its doing it. You didnt really provide alot of context in your post, so I am just guessing that you just dont understand what is actually happening.

    So, (x,y) is your multi dim'd array, with x being rows and y being columns, right?

    So if you were to manually assign them values you'd do it like this (arranged to make sense visually, please never use command seperators).

    arr(0,0)="this": arr(0,1)="that" : arr(0,2)="other"
    arr(1,0)="this": arr(1,1)="that" : arr(1,2)="other"
    arr(2,0)="this": arr(2,1)="that" : arr(2,2)="other"
    

    This is the order that the loops will assign value to them, from up to down, left to right. Another thing that I think ought to be pointed out here is:

    from 0 to UBOUND(array, dimension)
    

    I think this is lazy. I think its way better to fully define such as:

    from LBOUND(array, dimension) to UBOUND(array, dimension)
    

    But totally up to you.

    I hope this helps you.