Declaring Arrays

Because an array is a variable, you must declare it the same way 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 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 the array will hold. An array can hold any of the following data types: Integer, Long, Single, Double, Variant, Currency, String, Boolean, Byte, Date.

When you declare an array, Visual Basic automatically reserves enough memory space for it. The amount of 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 — two bytes for each element of the array (recall that the size of the Integer data type is 2, hence 2*6 = 12). The larger the array, the more memory space is required to store the data. Because arrays can eat up a lot of memory and impact your computer's performance, it is recommended that you declare arrays with only as many elements as you think you'll use.

0 0

Post a comment