Visual Basic 6.0 Guide
Loops - Repetition

For ... Next

There are at least 6 different ways to make Visual Basic repeat a section of code. The simplest method is to use a For and Next loop.

For example,

Private Sub Form_Load()
Form1.Show
Dim intCounter As Integer
For intCounter = 1 To 10
Print intCounter
Next intCounter
End Sub

The above code will print the numbers from 1 through to 10 onto the form when the program loads. You can see that the general structure of the loop is as follows.

For variable = startValue To endValue
Statement(s)
Next variable

The items in bold change depending on how many times you want the code to run. You can repeat as many lines of code as you need between the For and Next statements. The start and end values can also be variables.

Simple Tasks

Adapt the code from the example above to get your program to do the following things

  • Write the numbers from 1 to 20 on the form.
  • Write the numbers from 50 to 60 on the form.

Making Multiplication Tables

Let's start with a straightforward idea. We want to make a program that will display the multiplication table for a small number. Try the following code and write down what each of the lines of code do in the program.

Private Sub Form_Load()
Form1.Show
Dim intCounter As Integer
Dim intTables As Integer
Dim intResult As Integer
intTables = 7
For intCounter = 1 To 12
intResult = intCounter * intTables
Print intCounter & " x " & intTables & " = " & intResult
Next intCounter
End Sub

Simple Task

Adapt the code that you have just written so that it prints out the multiplication table for a number other than 7. Which line do you have to change?

Extending The Program

The program would be better if the user was able to enter the number of the multiplication table that they want to see. It would be better to put the table in a text box rather than on the form itself too.

tables program form design

Private Sub cmdMakeTables_Click()
Dim intCounter As Integer
Dim intTables As Integer
Dim intResult As Integer
intTables = txtTables.Text
txtOutputTable.Text = ""
For intCounter = 1 To 12
intResult = intCounter * intTables
txtOutputTable.Text = txtOutputTable.Text & intCounter & " x " & intTables & " = " & intResult & vbNewLine
Next intCounter
End Sub

The Step Parameter

In the loops that you have used so far, the counter always goes up by 1 each time the loop repeats itself. You can make the loop behave differently by setting the Step parameter to a number other than 1. For example,

Private Sub Form_Load()
Form1.Show
Dim intCounter As Integer
For intCounter = 2 To 20 Step 2
Print intCounter
Next intCounter
End Sub

Simple Tasks

  • Change the above code so that the loop displays all of the odd numbers between 1 and 30.
  • Change the code so that the loop counts backwards from 15 to 1.