The For Loop

The For loop (sometimes referred to as the For...Next loop) also creates a loop. Unlike the Do loops, however, the For loop repeats for a specified number of times. The format of the For loop looks a little more daunting than that of the Do loops, but after you master the format, you'll have little trouble implementing For loops when your code needs to repeat a section of code for a specified number of times.

There isn't one correct loop to use in all situations. The For statement provides the mechanism for the fifth Visual Basic loop block that you'll learn. A For loop always begins with the For statement and ends with the Next statement. Here is the format of the For loop:

For CounterVar = StartVal To EndVal [Step IncrementVal]

Block of one or more

Visual Basic statements

Next CounterVar

A simple example will help demonstrate how the For loop works. The loop in Listing 8.4 computes the total of the numbers from 1 to 10.

Listing 8.4. Add the numbers from 1 to 10.

1: intSum = 0

2: For intNumber = 1 To 10

3: intSum = intSum + intNumber

4: Next intNumber

intNumber is the CounterVar in the format of the For Loop. The CounterVar must be a variable and not a control or a literal. 1 is the For loop's StartVal. The StartVal can be either a number, an expression, or a variable. 10 is the EndVal. EndVal can be either a number, an expression, or a variable. There is no Step specified here. In the For statement's format, the Step IncrementVal is optional (as you can tell from the format's square brackets). If you don't specify a Step value, Visual Basic assumes a Step value of 1. Therefore, both of the following For statements do exactly the same thing:

For intNumber = 1 To 10

For intNumber = 1 To 10 Step 1

Listing 8.4's summing For loop initially assigns the StartVal to the CounterVar in the second line. Therefore, intNumber is assigned 1 at the top of the loop. Visual Basic then executes the body of the loop using the value 1 for intNumber. With intNumber being equal to 1, the third line works as follows, the first time through the loop:

intSum = intSum + 1

When Visual Basic executes the Next intNumber statement, Visual Basic returns to the top of the loop (the For statement), adds the Step value 1 to intNumber, and continues the loop again using 2 as intNumber in the loop's body. Therefore, the second time through the loop, the third line becomes this:

intSum = intSum + 2

The loop continues, adding the default Step value 1 to intNumber each time the loop executes. When intNumber becomes 10 (the format's EndVal), the loop finishes and the statement following the Next statement continues.

tip

Remember, the For loop terminates when the CounterVar becomes larger than the EndVal. There's an exception to this: If you code a negative Step value, the loop terminates when the CounterVar becomes smaller than the EndVal, as you'll see a little later in this section.

You don't need a For statement to sum the values 1 through 10. You could code one long assignment statement like this:

intSum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

You could also code back-to-back assignment statements like this:

IntSum = IntSum + 1

IntSum = IntSum + 2

IntSum = IntSum + 3

IntSum = IntSum + 4

IntSum = IntSum + 5

IntSum = IntSum + 6

IntSum = IntSum + 7

IntSum = IntSum + 8

IntSum = IntSum + 9

IntSum = IntSum + 10

Neither of these approaches is extremely difficult, but what if you needed to add the first 100 integer numbers? The previous assignments could become tedious indeed, but with the For loop it's as easy to add the first 100 integers as it is to add the first 10 integers, as Listing 8.5 demonstrates.

Listing 8.5. Add the numbers from 1 to 100.

1: IntSum = 0

2: For intNumber = 1 To 100 ' Only this line changes

3: IntSum = IntSum + IntNumber

4: Next intNumber

The following loop displays five message boxes:

For intCtr = 1 To 20 Step 4

intPress = MsgBox("This is a message box")

Next intCtr

The loop counts up from 1 to 20 by 4s, putting each count into the counter variable named intCtr and printing a message box each time. The Step value changes how Visual Basic updates the CounterVar each time the loop iterates.

note

An iteration is one complete cycle through a loop.

If you specify a negative Step value, Visual Basic counts down. The following loop rings the PC's speaker five times:

For intCtr = 5 To 1 Step -1

Beep

Next intCtr

note

The Beep statement simply buzzes the speaker on your computer.

caution

If you specify a negative Step value, EndVal must be less than StartVal or Visual Basic will execute the loop only once.

Listing 8.6 contains a fairly comprehensive For loop that computes compound interest for an initial investment of $1,000.00. The code appears inside the Click event procedure for a command button named cmdIntr. With compound interest, each year the amount of money invested, including interest earned so far, compounds to build more money. Each time period, normally a year, means that another year's interest must be added to the value of the investment. A For loop is perfect for calculating interest. Listing 8.6 uses five compound cycles.

Listing 8.6. Using a For loop to calculate compound interest.

1: Sub cmdIntr_Click ()

2: ' Use a For loop to calculate a final total

3: ' investment using compound interest.

4: '

5: ' intNum is a loop control variable

6: ' sngIRate is the annual interest rate

7: ' intTerm is the Number of years in the investment

8: ' curInitInv is the investor's initial investment

9: ' sngInterest is the total interest paid

10: Dim sngIRate As Single, sngInterest As Single

11: Dim intTerm As Integer, intNum As Integer

12: Dim curInitInv As Currency

13:

14: sngIRate = .08

15: intTerm = 5

16: ' Watch out... The Code window might convert the

17: ' following literals, 1000.00 and 1.0, to double-

18: ' precision literals with the suffix # to ensure

19: ' accuracy.

20: curInitInv = 1000.00

21: sngInterest = 1.0 ' Begin at one for first compound

22:

23: ' Use loop to calculate total compound amount

24: For intNum = 1 To intTerm

25: sngInterest = sngInterest * (1 + sngIRate)

26: Next intNum

27:

28: ' Now we have total interest,

29: ' calculate the total investment

30: ' at the end of[]years

31: lblFinalInv.Caption = curInitInv * sngInterest

32: End Sub

This analysis focuses on the loop and not the interest calculation. The most important thing that you can do at this point is to master the For looping statement. The code's remarks contain variable descriptions so that anyone looking at the code or changing the code later will know what the variables are for.

After the program defines all the variables, the variables are initialized with start-up values. If you use this event procedure, be sure to add a label named lblFinalInv to a form and add a command button named cmdInt to the form. The middle lines will seem to give you trouble as you type them unless you remember the description you learned in Hour 5, "Putting Code into Visual Basic," of data suffix characters. Visual Basic uses the pound sign (#), to indicate double-precision values, and Visual Basic will assume that 1000.00 is a double-precision value (I don't know why) and will convert the 1000.00 to 1000# right after you press Enter at the end of the line. In addition, Visual Basic converts the 1.0 to 1# on the next line. Don't worry about Visual Basic's pickiness here.

The most important part of this program is the For loop that iterates through each interest rate period (five of them) and compounds the interest on top of the investment to date. Again, don't let the financial part worry you. The calculation is less important than understanding the looping process. After the loop finishes, the event procedure places the compounded investment in the label's Caption property.

sidebar

You Can Terminate Loops Early

Sometimes, you'll be processing user input or several data values using looping statements, and an exception occurs in the data that requires an immediate termination of the loop. For example, you might be collecting sales values for a company's 10 divisions inside a For loop that iterates 10 times. However, the user can enter 0 for a division's sales value, indicating that there is no sales data for that division. Rather than complete the loop, your program might need to quit the loop at that point because the full divisional report information can't be gathered at the time.

The Exit Do and the Exit For statements automatically terminate loops. No matter what the Do loop's comparison test results in, or how many more iterations are left in a For loop, when Visual Basic encounters an Exit Do or Exit For statement, Visual Basic immediately quits the loop and sends execution down to the statement following the loop.

Typically, an If statement triggers one of the Exit statements like this:

For intDivisions = 1 To 10

' Code to get a sales value

If (cngSales <= 0.0) Then

Exit For ' Quit the loop early

End If

' Process the rest of the code

Next intDivisions

The If ensures that the Exit For executes only under one specific condition (a missing sales value). Without that specific condition triggering the Exit For, the loop cycles normally. Visual Basic also supports the Exit Sub statement that terminates a procedure early.

note

I don't recommend that you rely on the Exit statement to bail out of control blocks and procedures. Most experienced programmers will not use the exit function. The Exit statement has a nasty habit of creating multiple exit points for a block of code, which normally makes the code harder to understand and maintain.

Top Home