Visual Basic Arrays

PreviousTable of ContentsNext
Visual Basic Do ... LoopsVisual Basic Multidimensional Arrays


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99


In Understanding Visual Basic Variable and Constant Types and Declaring Visual Basic Variables and Constants we looked at storing data (such as numbers, strings and boolean true or false values) in memory locations known as variables and constants. The variable types covered in those chapters were useful for storing one value per variable. Often, however, it is necessary to group together multiple variables into a self contained object. This is where the concept of Visual Basic Arrays comes in.

What is a Visual Basic Array

<google>ADSDAQBOX_FLOW</google> A Visual Basic array is an object that contains a specified number of variables of the same type. Once you have grouped all the variable values into the array you can then perform tasks like sorting the array items into alphabetical or numerical order, accessing and changing the value assigned to each array item, and passing the group of items as a parameter to a Visual Basic Function or Subroutine (see Visual Basic Modules and Procedures) by passing just the array object.

In this chapter we will look in detail at how to create and manipulate single Visual Basic arrays. The next chapter will cover Visual Basic Multidimensional Arrays.

Each value in an array is known as an array element. The pointer to the location of a specific element in an array is called an index.

How to Declare a Visual Basic Array

An array is declared using the Dim keyword. The syntax is as follows:

Dim arrayname(size) As dataType

The arrayname is the name by which the array will referenced in code. The size value in parentheses defines the maximum size of the array. It is important to note that array elements are numbered starting from 0, so an array of size 10 actually holds 11 elements (indexed as 0 though to 10).

Finally, the dataType value defines the type of variable the array will hold.

The following Visual Basic code excerpt declares an array capable of containing 6 String variables:

Dim strColors(5) As String

Initializing a Visual Basic Array

As with other variable types, an array can be initialized during the declaration. This is achieved by encapsulating comma separated element values in braces ({}). Note that when initializing an array, it is not necessary to specify the array dimension:

The following example initializes our colors array:

Dim strColors() As String = {"Red", "Green", "Blue", "Indigo", "Violet", "Yellow" }

Similarly, an Integer array would be initialized as follows:

Dim intNumbers() As Integer = { 12, 43, 33, 45, 63 }

Assigning Values to Individual Array Elements

Once an array has been declared it is often necessary to change the value of a particular array element. This is performed by referencing the array and the index of the element to be changed (keeping in mind that the first element of an array is index position 0).

For example, to change the value of the first element of a String array:

strColors(0) = "Orange"

Similarly, to change the second value of an Integer array:

intNumbers(1) = 25

A For loop can also be used to assign multiple values to an array. The following code excerpt loops through the elements of an array assigning the current value of the loop counter to the corresponding array index:

Dim intNumbers(10) As Integer
Dim intCount As Integer

For intCount = 0 To 10
     intNumbers(intCount) = intCount
Next intCount

Accessing Array Element Values

Accessing an element in a Visual Basic array is similar to assigning a value to an array element. All that is required is the array name and the index of the element to be accessed. The following Visual Basic code excerpt displays MessageBoxes containing the string value the first and seconds elements in the strColors array:

Dim strColors(5) As String = {"Red", "Green", "Blue", "Indigo", "Violet", "Yellow" }

MessageBox.Show(strColors(0))
MessageBox.Show(strColors(1))

A For loop can also be used to iterate through each element of an array:

Dim strColors(5) As String = {"Red", "Green", "Blue", "Indigo", "Violet", "Yellow" }
Dim intCount As Integer

For intCount = 0 To 10
     MessageBox.Show(strColors(intCount))
Next intCount

Finding the Size of an Array

The size of an array (i.e. the number of elements contained in the array) can be obtained by accessing the Length property of the specific array.

For example, to find out the size of the strColors array:

Dim strColors(5) As String = {"Red", "Green", "Blue", "Indigo", "Violet", "Yellow" }
Dim intArraySize As Integer

intArraySize = strColors.Length

Another way to be sure you do not exceed the bounds of a Visual Basic array is to use the UBound() and LBound() functions. These functions return the upper and lower bounds of an array respectively. This is especially useful when using a For loop to iterate through an array. For example:

Dim intNumbers(10) As Integer
Dim intCount As Integer

For intCount = LBound(intNumbers) To UBound(intNumbers)
     MessageBox.Show (intNumbers(intCount))
Next intCount

Changing the Size of a Visual Basic Array

Once an array has been declared, its size can be changed using either a destructive or non-destructing approach. The Visual Basic ReDim keyword destroys the array and then recreates it thus losing any data held in the array. ReDim is useful for re-using an existing array, but of little use in terms of dynamically resizing that array since all data is lost.

The following Visual Basic code destructively changes the size of an array:

Dim strColors() = {"Red", "Green", "Blue"}

ReDim strColors(10)

An array can be resized without destroying the element data using the Visual Basic Array.Resize() function. This function accepts two parameters, the array to be resized and the new size of the array. The following example non-destructively resizes an existing array:


Dim strColors() = {"Red", "Green", "Blue"}

Array.Resize(strColors, 10)

Clearing a Element Ranges from a Visual Basic Array

The contents of array elements may be cleared using the Array.Clear() function. This function takes three parameters, the array, the start index and the number of elements from the index to clear.

The following code sample clears two elements starting at the second element (keep in mind that the elements begin at index 0):

Dim strColors() = {"Red", "Green", "Blue", "Yellow"}

Array.Clear(strColors, 1, 2)

Sorting a Visual Basic Array

An array may be sorted using the Visual Basic Array.Sort() function. The Array.Sort() function accepts an array as a parameter and sorts the elements in the array into alphabetical order.

In the following code sample, the order of the elements in the strColors array is sorted alphabetically:

Dim strColors() = {"Red", "Green", "Blue"}

Array.Sort(strColors)

The Visual Basic Array.Reverse() function may be used to reverse the order of elements in an array. It is particularly useful to call this function after calling the Array.Sort() function to sort elements into reverse order:

Dim strColors() = {"Red", "Green", "Blue"}

Array.Sort(strColors)

Array.Reverse(strColors)

Searching for Array Elements

Visual Basic provides a mechanism finding elements in an array. The Array.BinarySearch() function searches the specified array for a matching element and returns the index of the matching element:

Dim strColors() = {"Red", "Green", "Blue"}
Dim intMatchIndex As Integer

intMatchIndex = Array.BinarySearch(strColors)


Purchase and download the fully updated Visual Basic 2010 edition of this eBook in PDF and ePub for only $9.99