Basic Array Usage

An array is a set of indexed elements that have the same data type. An array allows you to declare a single variable with many individual compartments. You declare arrays the same as you would any other variable with the exception that you generally specify the size of an array (the number of elements it can contain) when you declare it. An array whose size is specified in its declaration is said to be a fixed-length array. Alternatively, if you don't specify a size when you declare an array, a dynamic array is created. A dynamic array is an array whose size can be altered at run-time or during the execution of your code. Listing 3.6 contains some sample array declarations.

Listing 3.6: Sample Array Declarations

' Declare an array of integers with 26 elements Dim anIntegerArray(25) As Integer

' Declare a two-dimensional long array ' with 10 rows and 15 columns Dim a1LongArray(9, 14) As Long

' Declare a dynamic array of variants Dim avVariantArray() As Variant

By default, the index of an array begins with 0. That is why the array declarations above contain one more element than the number specified in the declaration. If you specify Option Base 1 at the top of your module, then the index of your arrays will begin with 1 rather than 0.

The second array declared in Listing 3.6 contains two dimensions. You can declare arrays with up to 60 dimensions. A word of warning however—multidimensional arrays can quickly sap your system resources, so if you're using more than a few dimensions, you'll want to keep an eye on the number of elements so that you can estimate the total impact on your system. To estimate the memory required by an array, take the product of the number of elements in each dimension times the storage size of the underlying data type. For example, consider the following array:

Dim adBigDoub1eArray(10, 25, 50, 50) As Double

This declares a four-dimensional array containing 11 * 26 * 51 * 51 elements or 743,886 elements. It takes 8 bytes to store a single double variable, so the memory requirement of this array is 743,886 * 8 bytes (5,951,088 bytes).

Was this article helpful?

0 0

Post a comment