• Status: Solved
• Priority: Medium
• Security: Public
• Views: 3740

How can I convert a 1D array into a 2d array

I have an one dimensional array of comma delited values.  Does any know in VBA how I would turn this into a 2 dimensional array?

So if I have
arry(1)="a,b,c"
arry(2)="x,4,3"

I need it to be

arry(1,1)="a"
arry(1,2)="b"
arry(1,3)="c"

arry(2,1)="x"
arry(2,2)="4"
arry(2,3)="3"

I tried using split and a For loop but nothing seems to work.?
0
drhamel69
1 Solution

Commented:
0

Commented:
Try this:
``````Dim arry(2) As String
Dim target(,) As String

arry(0) = "alpha,beta,gamma"
arry(1) = "a,b,c"
arry(2) = "x,4,3"

For i As Integer = 0 To arry.Length - 1
Dim parts() As String = arry(i).Split(","c)

ReDim Preserve target(arry.Length - 1, parts.Length - 1)

For j As Integer = 0 To parts.Length - 1
target(i, j) = parts(j)
Next
Next
``````
0

Commented:
Sorry...  that was .NET. This should be VBA friendly  : )
``````Dim arry(2) As String
Dim target(,) As String

arry(0) = "alpha,beta,gamma"
arry(1) = "a,b,c"
arry(2) = "x,4,3"

For i As Integer = 0 To arry.Length - 1
Dim parts() As String = Split(arry(i), ",")

ReDim Preserve target(UBound(arry), UBound(parts))

For j As Integer = 0 To parts.Length - 1
target(i, j) = parts(j)
Next
Next
``````
0

Commented:
*Ugh*

Change line 13 to:
``````For j = 0 To UBound(parts)
``````
0

Commented:
You need a module in which you set the option base to 1

Option Base 1

'code here that creates the one dimension array Arry()

Dim Arry2D (3,2) as Variant, i as integer, j as integer

For i = 1 to 2
For j = 1 to 3
Arry2D(i,j) = Split Arry(i)(j)
Next j
Next i
0

Commented:
One line of code :) 'OK, 2 lines with Dim

'Note - to access arrNew items, use arrNew(i)(j) instead of arrNew(i,j) like:
Dim i, j
For i = 0 To 1
For j = 0 To 2
Debug.Print i; ","; j, arrNew(i)(j)
Next j
Next i
``````Dim arrNew As Variant
arrNew = Array(Split(arry1(1), ","), Split(arry1(2), ","))
``````
0

Commented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.