How do I work with arrays?

This tutorial is understandable for someone who knows the basics of Visual Basic.
The key to programming with arrays is to learn how to work with loops, especially the for...next loop. So that's what I'm going to explain.

1: Create a new Visual Basic project. First make one label in the upper-left corner of the form. Give it a width of around the 2000 twips and a height of 1000 twips. Then select the label by clicking on it and copy the label. Then click on paste or press Ctrl V. Visual Basic asks if you want to create a control array. Click on yes and you've created another label with the same properties as the first, even the name is the same. Only the index property differs from the first. The first label has a index of 0, the second of 1. Place the label below the first one. This way, paste 3 other labels, so there's a row of labels. If the form is too small, enlarge the form. All the labels have a different index, from 0 to 4, that form a array. The first label is label1(0), the second label1(1), the third label1(2), etc.

2: Now we're going to do something with this array. This can be done with the help of a loop. Paste this code into the Form_Load event:

For i = 0 To 4
Label1(i).Caption = "This is label: " & i + 1
Next i

This loop runs 5 times, when i = 0, 1, 2, 3 and 4. Every time the loop runs, the label with a index of i will be given a caption. This saves a lot of time. You have to declare i if you work with Option Explicit.

3: You can also declare arrays with some code. Let's declare an array named X with 10 different values of the integer type.

Dim X(10) As Integer

4: Now we're going to give some values to X(1), X(2), etc. and show them with the help of a label. First make a label next to the other labels. Give it a width of 3000, a height of 500 and a empty caption. Also make a command button.

5: Doubleclick on the command button and paste the following code into the Command1_Click event:

For i = 1 To 10
X(i) = i * 10
Label2.Caption = Label2.Caption & " " & X(i)
Next i

This is a loop that gives X(1) a value of 10, X(2) a value of 20, etc. Then label2 shows the array.

That was it!
You can download this tutorial by clicking
HERE.

If you have any questions or comments or whatever, click HERE to sent me a e-mail.

<-- Back to tutorials