Vba Arrays Using Arrays: Changing The Lower Bound
Vba Arrays Using Arrays: Changing The Lower Bound
Using arrays
o
You can declare an array to work with a set of values of the same data type. An array
is a single variable with many compartments to store values, while a typical variable
has only one storage compartment in which it can store only one value. Refer to the
array as a whole when you want to refer to all the values it holds, or you can refer to
its individual elements.
For example, to store daily expenses for each day of the year, you can declare one
array variable with 365 elements, rather than declaring 365 variables. Each element in
an array contains one value. The following statement declares the array variable with
365 elements. By default, an array is indexed beginning with zero, so the upper
bound of the array is 364 rather than 365.
VBCopy
Dim curExpense(364) As Currency
To set the value of an individual element, you specify the element's index. The
following example assigns an initial value of 20 to each element in the array.
VBCopy
Sub FillArray()
Dim curExpense(364) As Currency
Dim intI As Integer
For intI = 0 to 364
curExpense(intI) = 20
Next
End Sub
VBCopy
Option Base 1
Dim curExpense(365) As Currency
You can also explicitly set the lower bound of an array by using a To clause, as shown
in the following example.
VBCopy
Dim curExpense(1 To 365) As Currency
Dim strWeekday(7 To 13) As String
VBCopy
Dim varData(3) As Variant
varData(0) = "Claudia Bendel"
varData(1) = "4242 Maple Blvd"
varData(2) = 38
varData(3) = Format("06-09-1952", "General Date")
The other way is to assign the array returned by the Array function to
a Variant variable, as shown in the following example.
VBCopy
Dim varData As Variant
varData = Array("Ron Bendel", "4242 Maple Blvd", 38, _
Format("06-09-1952", "General Date"))
You identify the elements in an array of Variant values by index, no matter which
technique you use to create the array. For example, the following statement can be
added to either of the preceding examples.
VBCopy
MsgBox "Data for " & varData(0) & " has been recorded."
If you think of the array as a matrix, the first argument represents the rows and the
second argument represents the columns.
VBCopy
Sub FillArrayMulti()
Dim intI As Integer, intJ As Integer
Dim sngMulti(1 To 5, 1 To 10) As Single
See also
Visual Basic conceptual topics