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] ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access