View Single Post
  #8   Report Post  
Posted to microsoft.public.excel.programming
Ken Johnson Ken Johnson is offline
external usenet poster
 
Posts: 1,073
Default Multi Dimensional Array

Hi Andy,

Please forgive my stupidity!

As Nick stated, when using ReDim Preserve, you can only change the size
of the LAST dimension, so you forget about rows staying as rows and
columns staying as columns.

When the code is looking at your worksheet it is always taking values
from 3 columns but the number of rows it takes data from is increasing
up to a final unknown number (Although it can't be bigger thwn the
total number of rows being searched.

Because of these facts(rows are changing, columns fixed at 3,can only
resize array's 2nd dimension) you usually get your code to feed the
sheet column values into the array's fixed first dimension and the
sheet's row values into the array's resizeable last dimension.
So values on the worksheet that appear on the worksheet as 30 rows and
3 columns would produce an array with only 3 rows and 30 columns. If
you then need to place such an array back onto the worksheet you can
use the Transpose worksheet function.

The following code is (I hope) correct...

Option Base 1
Public Sub Populate_2D_Array()
Dim My2DArray() As Variant
Dim I As Integer
Dim J As Integer
Dim K As Integer
For I = 1 To 100
If ActiveSheet.Cells(I, 1).Value = 10 Then
K = K + 1
ReDim Preserve My2DArray(3, K)
For J = 1 To 3
My2DArray(J, K) = ActiveSheet.Cells(I, J).Value
Next J
End If
Next I
For I = 1 To UBound(My2DArray, 2)
Debug.Print My2DArray(1, I) & ", " & _
My2DArray(2, I) & ", " & _
My2DArray(3, I)
Next
End Sub

Check out the values printed in the Immediate window.

Ken Johnson