Single Dimension Arrays

Using the keywords Dim, Static, Public, and Private, arrays are created just like any other variable.

Unless Option Base 1 is specified, or dimensioned, with an explicit range, arrays by default begin with a zero base index.

• Dim myIntegerArray(5) As Integer ' Creates six Integer elements

• Dim myVariantArray(10) ' Creates eleven Variant elements

• Dim myStringArray(1 to 7) As String ' Creates 7 String elements

In the preceding declarations, the number of elements in an array is determined during array declaration using either a number or a range of numbers surrounded by parentheses.

A nice feature of VBA is its ability to initialize variables for use. Specifically, VBA initializes number-based array elements to 0 and string-based array elements to "" (indicating an empty string).

Individual elements in an array are accessed via an index: lblArrayValue.Caption = myStringArray(3)

The next Click event procedure initializes a String array using a For loop and adds the array contents to a list box.

Private Sub cmdPopulateListBox_Click()

' Declare a seven element String array. Dim myStringArray(1 To 7) As String Dim x As Integer

' Initialize array elements. For x = 1 To 7

myStringArray(x) = "The value of myStringArray is " & x

Next x

lstMyListBox.Addltem myStringArray(x)

Next x

End Sub

VBA provides two array-based functions called LBound and UBound for determining an array's upper and lower bounds. The LBound function takes an array name and returns the array's lower bound. Conversely, the UBound function takes an array name and returns the array's upper bound. These functions are demonstrated in this Click event procedure.

Private Sub cmdPopulateListBox_Click()

' Declare an eleven element Integer array. Dim myIntegerArray(10) As Integer Dim x As Integer

' Initialize array elements using LBound and UBound functions

' to determine lower and upper bounds.

For x = LBound(myIntegerArray) To UBound(myIntegerArray)

mylntegerArray(x) = x Next x

' Add array contents to a list box.

For x = LBound(mylntegerArray) To UBound(mylntegerArray)

IstMyListBox.Addltem mylntegerArray(x) Next x End Sub

0 0

Post a comment