Declaring Arrays

Because an array is a variable, you must declare it in a similar way that you declare other variables—by using the Dim statement. When you declare an array variable, you set aside the required memory space to hold its values. Let's take a look at some examples of array declarations:

Dim cities(6) As String Dim daysOfWeek(7) As String Dim lotto(6) As Integer Dim exchange(5, 3) As Variant

Notice that the names of variables are followed by some numbers in parentheses. One-dimensional arrays require one number between parentheses. This number specifies the maximum number of elements that can be stored in a list. The name of a two-dimensional array is always followed by two numbers—the first number is the row index, and the second number is the column index. In the example above, the exchange array can hold a maximum of 15 values (5*3=15).

The last part in the array declaration is the definition of the data type that the array will hold. An array can hold any of the following data types: Integer, Long, Single, Double, Variant, Currency, String, Boolean, Byte, or Date.

When you declare an array, Visual Basic automatically reserves enough memory space. The amount of the memory allocated depends on the array's size and data type. When you declare a one-dimensional array named lotto with six elements, Visual Basic sets aside 12 bytes—2 bytes for each element of the array (recall that the size of the Integer data type is 2 bytes, hence 2*6 = 12). The larger the array, the more memory space required to store the data. Because arrays can eat up a lot of memory and impact your computer's performance, it's recommended that you declare arrays with only as many elements as you think you'll use.

0 0

Post a comment