O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

LOOPING STATEMENTS

Looping statements make the program execute a series of statements repeatedly. The loop can run for a fixed number of repetitions, run while some condition is True, or run while some condition is False.

Broadly speaking, there are two types of looping statements. For Next loops execute a certain number of times that (in theory at least) is known. For example, a For Next loop may execute a series of statements exactly 10 times. Or, it may execute the statements once for each object in a certain collection. If you know how many items are in the collection, you know the number of times the loop will execute.

A While loop executes while a condition is True or until a condition is met. Without a lot more information about the application, it is impossible to tell how many times the code will execute. For example, suppose a program uses the InputBox function to get names from the user until the user clicks the Cancel button. In that case, there’s no way for the program to guess how many values the user will enter before canceling.

The following sections describe the looping statements supported by Visual Basic .NET. The next two sections describe For Next loops, and the sections after those describe While loops. (Example program Loops, which is available for download on the book’s website, demonstrates some of these kinds of loops.)

For Next

The For Next loop is the most common type of looping statement in Visual Basic. The syntax is as follows:

For variable [As data_type] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required