Chapter 19. Repeating Program Steps

One of the computer's greatest strengths is its ability to perform an action repeatedly without getting bored or making careless mistakes. It can calculate the average test scores for a dozen students, print 100 party invitations, or compute the monthly bills for a million customers with no trouble or complaining.

The lessons you've read so far, however, don't tell you how to do these things. Until this point, every step the computer takes requires a separate line of code. To add 10 numbers, you would need to write 10 lines of code (or one long one).

In this lesson you learn how to make the computer execute the same lines of code many times. You learn how to loop through arrays and collections of items to take action or perform calculations on them.

The following sections describe the kinds of loops provided by Visual Basic. The final section describes two statements you can use to change the way a loop works: Exit and Continue.

FOR LOOPS

A For loop uses a variable to control the number of times it executes a series of statements. The For loop's syntax is as follows:

For variable[As datatype] = start To stop [Step amount]
    statements...
Next [variable]

Where:

  • variable — This is the looping variable that controls the loop.

  • [As datatype] — If present, this declares the looping variable's data type. This gives the variable the loop's scope so it is not visible outside the loop. Usually the data type is Integer.

  • start — This is the looping variable's initial ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.