Visual Basic Loops

This article, we will be dealing with ways to have your program perform the same task a number (not necessarily known at the time you start programming) of times.

For… Next…

Using the For.. Next statement, you can set code to run a predefined number of times. As an example, let’s build a small application that asks the user for a number. The application will then add up all the even numbers from 0 to that number (or all odd numbers if that’s what the user wants).

We start by creating the interface. Add the following controls to your form.

We use the frame to more or less group the two optionbuttons. That way, when a user sees the application, it will immediately be clear that the two optionbuttons are ‘grouped’, and that it’s only possible to select one of the two. (As an added bonus, VB will recognize the OptionButtons are grouped, and if one is selected, the other will automatically be deselected).

You do this by first drawing the frame on the form, and then drawing the OptionButtons in the Frame. The end result should look something like this.

Ok, so we have the interface. Let’s spend a minute thinking on what the Program is supposed to do. The user will enter a number, select either odd or even, and our program will add all the numbers from 0 to the specified number. The way we will handle this is by using the For.. Next statement. First of all, let’s look at the syntax for the statement:

For counter = start To end [Step step]


Next [counter]

Basically, you specify a counter (usually a variable), and you specify the inital (start) value, as well as the end value. The code to be executed every time is specified in between the ‘For’ and the ‘Next’ statement (The [statements] in the above quote). The Step-part can be used in case you want to skip a certain number of items in between. (Note: You can also use a negative number here).

If we look back at our program, if a user selects ‘Even’, we will calculate all values from 0 to whatever number was entered. The tricky part is that not all numbers are odd. We could code a way to determine whether or not a number is odd or even, but why not keep it more simple than that? We know that every other number will be even. So we just start at 0, skip the odd number 1 (which we will achieve by setting the ‘Step’ part of the For… Next statement to 2), and add the number to another variable.

If the user picked odd, we start at 1 instead of at 0, and also always skip a number. That’s basically it.

In code this would look something like this:

Private Sub cmdCalculate_Click()
‘ Declare variables
Dim intRange As Integer
Dim intResult As Long

‘ Check whether we need to calculare odd or even numbers
‘ Even was selected
If optEven.Value = True Then ‘ Even
For intRange = 0 To Val(txtNumber.Text) Step 2
intResult = intResult + intRange
Next intRange
‘ Odd was Selected
For intRange = 1 To Val(txtNumber.Text) Step 2
intResult = intResult + intRange
Next intRange
End If

MsgBox “Result:” & intResult
End Sub

Let’s look at what we did here. First we declare two variables, intRange, which will be the number used to ‘remember’ where we are when we loop between 0 (or 1) and the number specified by the user. We’ve made this variable an integer, which (as you know) limits the range of the to anything between -32,678 and 32,676. The other variable was made a Long. This is done because obviously the number will de bigger than the number contained in the integer.

Next, we check which OptionButton was selected. If it was the Even one (which is the default), we start intRange at 0. Else, we start at 1. (This is nice about using two OptionButtons. If the first one is NOT true, then the other must be).

Then comes the For Next statement:

For intRange = 0 To Val(txtNumber.Text) Step 2
intResult = intResult + intRange
Next intRange

We specify that intRange will contain anything between 0 and the specified number. This is where the program starts looping. First it sets intRange to 0, and runs the piece of code inbetween the For and the Next statements (in our case: intResult = intResult + intRange. It’s not hard to see what we do here, is it? We just use intResult to store the value in between. We just add the (at that moment) current value of intRange to it).

Finally, the Next intRange statement is called. To see this in a bit more detail, let’s look at all the things that would happen if we’d set the number to 10, and want all the even numbers added up.

# intRange will be set to run from 0 to 10.
# The loop begins (No, not a giggle loop). intRange is, at this point 0. intResult is also 0.
# 0 + 0 = 0, so intResult remains 0 for the moment. (You might find this a bit redundant, but from a mathematical perspective, this is the proper way to tackle this problem, I think).
# Next is called. intRage is now set to 2 (The step-part was set to 2, remember?).
# 0 + 2 = 2. intResult = 2.
# Next is called. intRange is set to 4.
# 2 + 4 = 6.
# Next is called. intRange is set to 6.
# 6 + 6 = 12.
# Next is called. intRange is set to 8.
# 12 + 8 = 20.
# Next is called. intRange is set to 10. (Not that 10 is the final value in the range. The For… Next-loop will end after this).
# 20 + 10 = 30.
# The user sees a MessageBox which displays the result

It is possible to exit the loop in between, by using the ‘Exit For’ statement. (If, for instance, you’d be trying to find a certain condition or number, and the number would be reached, you can prevent your program from running longer than necessary by using Exit For).

That’s it for For… Next. Let’s now take a look at Do-loops.

Do… Loop

Another way to deal with code that has to be used several times in a row is by using a Do… Loop-statement. You can choose from Do – While or Do – Until. Both accept a condition. While the condition is not true( when you use Until), the loop continues. Lets look at another example:

Dim x As Integer
Do Until x = 10
x = x + 1

MsgBox x

We could rewrite this code to make it into a Do… While statement like this:

Dim x As Integer

Do While x < 10 x = x + 1 Loop MsgBox x As you see, the While form is slightly different. While the condition is true, the loop continues. So what's the difference between Do... Loop and For... Next loops? Well, with For... Next, you usually know how many times something has to be looped, while using Do... Loop usually means you just know that a certain condition needs to be True.