Looping Statements


A looping statement makes the program execute a series of statements repeatedly. The loop can run for a fixed number of repetitions, run while some condition holds true, run until some condition holds true, or run indefinitely.

For Next

A For Next loop executes a piece of code while a loop control variable ranges from one value to another.

The syntax is as follows:

  For variable [As data_type] = start_value To stop_value [Step increment]     statements     [Exit For]     statements Next [variable] 

For Each

A For Each loop executes a piece of code while a loop control variable ranges over all of the items contained in a group class such as a collection or array.

The syntax is as follows:

  For Each variable [As object_type] In group     statements     [Exit For]     statements Next [variable] 

Do Loop

Do Loop statements come in three forms. First, if the statement has no While or Until clause, the loop repeats infinitely or until the code uses an Exit Do, Exit Sub, GoTo, or some other statement to break out of the loop.

The syntax is as follows:

  Do     statements     [Exit Do]     statements Loop 

The other two forms of Do Loop statements execute as long as a condition is true (Do While condition) or until a condition is true (Do Until condition).

The second form of Do Loop statement tests its condition before it executes, so the code it contains is not executed even once if the condition is initially false.

The syntax is as follows:

  Do {While | Until} condition     statements     [Exit Do]     statements Loop 

The third form of Do Loop statement tests its condition after it executes, so the code it contains is executed at least once even if the condition is initially false.

The syntax is as follows:

  Do     statements     [Exit Do]     statements Loop {While | Until} condition 

While End

The While End loop executes a series of statements as long as a condition is true. It tests its condition before it executes, so the code it contains is not executed even once if the condition is initially false.

The syntax is as follows:

  While condition     statements     [Exit While]     statements End While 

This statement is equivalent to the Do Loop:

  Do While condition     statements     [Exit Do]     statements Loop 

GoTo

GoTo performs an unconditional jump to a specified line.

The syntax is as follows:

      GoTo line_label     ... line_label:     ... 

Because undisciplined use of GoTo can lead to “spaghetti code,” which is difficult to understand, debug, and maintain, you should generally avoid using GoTo.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net