Changes

Visual Basic For Loops

1,843 bytes added, 18:23, 6 August 2007
Creating a Visual Basic For Loop
Next intCount
</pre>
 
For loops can also be nested. In a nested For Loop, the inner loop is executed for each iteration of the outer loop. For example:
 
<pre>
Dim intCount1, intCount2 As Integer
 
For intCount1 = 0 To 5
For intCount2 = 0 To 10
'VB code here
Next intCount2
Next intCount1
</pre>
 
== Incrementing a For Loop by a Value Greater Than 1 ==
 
By default Visual Basic increments the For counter variable by a value of 1. This number can be increased using the ''Step'' keyword at the end of the ''For'' header statement. For example, to increment the counter by 10:
 
<pre>
Dim intCount As Integer
 
For intCount = 0 To 100 Step 10
MessageBox.Show("Counter is currently: " + CStr(intCount))
Next intCount
</pre>
 
== Early Exit of a For Loop ==
 
it is often necessary to exit a For loop before it has completed the specified number of loop iterations. This is achieved using the Visual Basic ''Exit For'' statement. This is typically used in conjunction with a conditional ''If'' statement. The Following code example causes the loop to exit if the counter is equal to 3:
 
<pre>
Dim intCount As Integer
 
For intCount = 0 To 5
If intCount = 3 Then Exit For
MessageBox.Show("Counter is currently: " + CStr(intCount))
Next intCount
</pre>
 
== Continuing a For Loop ==
 
The ''Exit For'' command causes the For loop to exit entirely. Another option is to skip the remaining statements in a loop under certain circumstances, let continue to loop. This is achieved using the ''Continue For'' statement. The following example skips the code in the body of the For statement if counter is 3, and continues the loop at the next iteration:
 
<pre>
Dim intCount As Integer
 
For intCount = 0 To 5
If intCount = 3 Then Continue For
MessageBox.Show("Counter is currently: " + CStr(intCount))
Next intCount
<pre>