39
Arrays
39.1 Overview
This chapter deals with arrays. An array is a group of variables of the
same type sharing the same name and referenced individually using
an index. Vectors and matrices are good examples of one- and two-
dimensional arrays. The fi rst part of the chapter presents simple arrays.
Dynamic arrays (whose size can be changed at run time) are discussed
in the second part of the chapter. The chapter concludes with a section
on the use of arrays as parameters, including a subsection on the relation-
ship between arrays and worksheet ranges.
39.2 Simple Arrays
There are several ways to declare arrays, all using the Dim statement.
The simplest way to declare an array is simply to tell VBA the largest
value the array index can take. Unless you indicate otherwise, VBA
arrays always start with index 0. In the following macro, MyArray has
six elements numbered 0, 1, 2, . . . , 5.
Sub ArrayDemo1()
Dim MyArray(5)
Dim i As Integer
Dim Temp As String
For i = 0 To 5
MyArray(i) = i * i
Next i
Temp = “”
For i = 0 To 5
Temp = Temp & “ # “ & MyArray(i)
Next i
MsgBox Temp
End Sub
If you use ArrayDemo1 in a spreadsheet, here is the result: