revised 10/9/07
I wrote a macro to copy values from named ranges into arrays. In my first try I used a For..Next loop to read and copy values into arrays, and later I found out that I could just directly copy them from ranges into arrays. The only catch is that, when copying values from ranges, the values will be stored in 2-dimension arrays, even if your values are in a single-column (or single-row, multiple columns) range. Say if you have values from cell A1 - A10, values will be stored in arrays "ARRAY[1][1]" to "ARRAY[10][1]". Since I don’t know the number of values just yet, I declared dynamic arrays (Dim ARRAY as Variant, rather than Dim ARRAY[a][b] as Integer). Here’s the code (green fonts are comments, red are not in the actual code, but footnotes explained below):
Option Base 1
Option Explicit (Note 1)
Private NumArray1 As Variant, NumArray2 As Variant
Sub populateArray()
Dim myRange As Range, my2ndRange As Range
Set myRange = Range("NamedRange") ‘fixed range (Note 2)
Set my2ndRange = Range(Cells(2, 3), Cells(2, 3).End(xlDown)) ‘range size depends on user input (Note 3, 4)
‘Here we go, start populating data. It’s [destination array] = [source array].value
NumArray1 = myRange.Value (Note 5)
NumArray2 = my2ndRange.Value
‘test the results
Debug.Print "NumArray1[1,1] is " & NumArray1(1, 1) & ", & NumArray1[9,1] is " & NumArray1(94, 1)
Debug.Print "NumArray2[1,0] is " & NumArray2(1, 1) & ", & NumArray2[9,1] is " & NumArray2(9, 1)
End Sub
Note 1: option base 1 makes all arrays start with 1, rather than 0. Without specification, your first array will be stored in Array(0,0). In my example, my first value is in Array(1,1), 5th value is in Array(5,1), so on.
Note 2: one way to define a range is to use named ranges. This is good if the cells are pre-populated and won’t change. If the number of data cells will change, it’s better to use the next selection method.
Note 3: Range(A,B) selects all cells between cell A and cell B. Assume we don’t know the number of data cells, Range(Cells(r,c), Cells(r,c).End(xlDown)) is a good method. This is just like click on Cells(r,c), and then press Control + Shift + down arrow.
Note 4 One thing about Cells(). It’s Cells (row, column), so Cell C2 is Cells(2,3), not Cells(3,2)
Note 5 I see in many web forums and how-to sites that implements for..next or other fancy loops to populate arrays. It took me a while to figure out it can be as simple as this!