Loop statements allow you to execute one or more lines of code repetitively. Visual Basic supports the following loop statements:
Do……Loop : The Do……Loop executes a block of statements for as long as a condition is True. Visual Basic evaluates an expression, and if it’s True, the statements are executed. If the expression is False, the program continues and the statement following the loop is executed.
There are two variations of the Do……Loop statement. A loop can be executed either while the condition is True or until the condition becomes True. These two variations use the keywords While and Until to specify how long the statements are executed. To execute a block of statements while a condition is true, use the following syntax :
Do While condition
To execute a block of statements until the condition becomes True, use the following syntax :
Do Until condition
Another variation of the Do loop executes the statements first and evaluates the condition after each execution. This Do…Loop has the following syntax :
Loop While condition
Loop Until condition
For…..Next : The For…….Next loop is one of the oldest loop structures in programming languages. Unlike the Do….loop, the For …..Next loop requires that you know how many times the statements in the loop will be executed. The For…Next loop uses a variable(it’s called the loop’s counter) that increases or decreases in value during each repetition of the loop. The
For…..Next loop has the following syntax :
For counter=start to end[Step increment]
The keywords in the square brackets are optional. The arguments counter, start, end and increment are all numeric. The loop is executed as many times as required for the counter to reach the end value.
While ………Wend : The while……wend loop executes a block of statements while a condition is True. The while…..wend loop has the following syntax :
statement - block
If condition is true, all statements are executed and when the Wend statement is reached, control is returned to the While statement which evaluates condition again. If condition is still True, the process is repeated. If condition is False, the program resumes with the statement following the Wend statement.