Changes

Jump to: navigation, search

Visual Basic Do ... Loops

2,858 bytes added, 19:38, 6 August 2007
no edit summary
'''If''' ''expression'' '''Then Exit Do'''<br>
'''Loop'''<br>
 
The following code excerpt causes the ''Do ... Loop'' to exit when the ''intTotal'' variable reaches 10:
 
<pre>
Dim intTotal As Integer
 
Do
intTotal = intTotal + 1
If intTotal = 10 Then Exit Do
 
MessageBox.Show("intTotal = " + CStr(intTotal))
Loop
</pre>
 
Another way to use a ''Do Loop'' is to make use of the ''While'' keyword. A ''Do ... Loop'' which uses the ''While'' keyword will loop as long as the ''While'' expression evaluates to ''True''.
 
It is important to understand that the ''While'' keyword can be used either at the start or end of the loop. When it is possible that the loop will not have to executed at all (i.e the criteria may already be met before the loop executes) then the While should be placed at the start of the loop. Alternatively, when the loop will need to be executed at least once before the expression will evaluate to ''True'' then the ''While'' should be placed at the end of the loop. The syntax for these two uses are as follows:
 
'''Do While''' ''expression''<br>
''[VB Statements]]''<br>
'''Loop'''<br>
 
'''Do'''<br>
''[VB Statements]]''<br>
'''Loop While''' ''expression''<br>
 
The following code samples demonstrate both uses of the ''While'' keyword. Note that the second loop will never execute because the first loop has already increased the value of ''intTotal'' to 10.
 
<pre>
Dim intTotal As Integer
 
Do
intTotal = intTotal + 1
 
MessageBox.Show("intTotal = " + CStr(intTotal))
Loop While intTotal < 10
 
Do While intTotal < 10
intTotal = intTotal + 1
 
MessageBox.Show("intTotal = " + CStr(intTotal))
Loop
</pre>
 
 
The ''While'' loop causes the loop to continue until an expression ceases to evaluate to ''True''. In other words, as soon as the expression returns ''False'' the loop exists. The ''Until'' keyuword does the reverse, in other words the loop continues until an expression evaluates to ''true''. As long as the expression returns false, the loop continues.
 
As with the ''While'' loop the ''Until'' expression may be placed at the start or end of the loop:
 
'''Do Until''' ''expression''<br>
''[VB Statements]]''<br>
'''Loop'''<br>
 
'''Do'''<br>
''[VB Statements]]''<br>
'''Loop Until''' ''expression''<br>
 
The following code example shows the ''Do ... Until ... Loop'' in action:
 
<pre>
Dim intTotal As Integer
 
Do
intTotal = intTotal + 1
 
MessageBox.Show("intTotal = " + CStr(intTotal))
Loop Until intTotal > 10
 
Do Until intTotal > 10
intTotal = intTotal + 1
 
MessageBox.Show("intTotal = " + CStr(intTotal))
Loop
</pre>
 
As with the previous example, the second loop will not execute because the the intTotal variable already exceeds 10 as a result of the previous loop.

Navigation menu