Tuesday, August 4, 2009

Working with arrays

Before we get to today's lesson on common controls, we will cover a bit of programming theory on Arrays.
In VB, arrays work in much the same way as they do in all other languages you have studied. By definition an array is an indexed variable, meaning it is one variable with many parts, each part being referenced by an index number. The index number being numeric, it can be manipulated by loop statements, incremented, decremented, etc. An array can contain any valid data type and, if it is of the Variant type, can even contain elements of different types.
An array is declared like any other variable, with the addition of an index:


Dim Department(6) As String

will declare an array of 7 elements of the String type (we assume that it will be 7 Department names). The only problem with this declaration is that the index goes from 0 to 6. So, if you want the name of the sixth Department you have to specify Department(5), which can be confusing at times.
To work around this problem you can specify the starting index in the declaration:


Dim Months(1 To 12) As String

Thus, Months(1) is January and Months(12) is December.
You don't even have to start at 1. If your Sections are numbered 101 - 120 you can define an array:


Dim Sections(101 To 120) As Integer

One common method of manipulating arrays is to use For...Next loops:



No comments:

Post a Comment