Link to home
Start Free TrialLog in
Avatar of Joe Howard
Joe HowardFlag for United States of America

asked on

Merge two 1D arrays into one 2D array

Is it possible to merge two one dimensional arrays into one two dimensional array using VBA?

For example's sake:
arrSource1 = Jack, Rebbeca, John
arrSource2 = Fredrick, Larson, Higgins

arrDestination:
arrDestination(0, 0) = Jack, Fredrick
arrDestination(1, 1) = Rebbeca, Larson
arrDestination(2, 2) = John, Higgins
Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

for i = 0 to arrsource1.length-1
    arrdestination(i, i) = arrsource1(i) & arrSource2(i)
next
Avatar of Joe Howard

ASKER

Thanks Dan, you got me going in the right direction.

Sub Test()
    Dim i As Integer
    Dim arrSource1() As String, arrSource2() As String

    arrSource1 = Split("Jack,Rebbeca,John", ",")
    arrSource2 = Split("Fredrick,Larson,Higgins", ",")
    
    ReDim arrDestination(0 To UBound(arrSource1), 0 To UBound(arrSource2))
    
    For i = 0 To UBound(arrDestination)
        arrDestination(i, i) = arrSource1(i) & arrSource2(i)
        Debug.Print arrDestination(i, i)
    Next
End Sub

Open in new window

I really don't understand what you're trying to achieve.

Reserving space for your 2-dimensional array seems a bit wasteful, since you're using it as a 1-dimensional array anyway (you only use the diagonal, if you have a graphic representation).

You can simply use arrDestination(i) = arrSource1(i) & arrSource2(i)
Sometimes I need an element from the first dimension, and sometimes an element from the second dimension, that's why I must keep the elements separate.
You can try a dictionary:

Dim dict As Dictionary
     
Set dict = New Dictionary

For i = 0 To UBound(arrSource1)
        dict.Add = arrSource1(i), arrSource2(i)
Next
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@GrahamSkan: my brain is taking a break today.
I kept looking at the example and asking myself: why does he create a NXN table when he needs a dictionary?
It was obvious he needed to just create a 2XN table and be done :)
It's easy to get hold of the wrong end of the stick when it's presented that way.