The For Next Loop , execute the loop body to the fixed number of times.
For Countervariable=[starting Value] To [ending Value] [Step]
[loop of the Body]
Next [countervariable]
countervariable : The counter for the loop to repeat the steps.
startingValue : The starting value assign to counter variable .
endingValue : When the counter variable reach end value the Loop will stop .
loop of the Body : The source code between loop body
Lets take a simple real time example , If you want to show a messagebox 5 times and each time you want to see how many times the message box shows.
Dim a,b,i As Integer
1. a=1
2. b = 5
3. For i = a To b
4. MsgBox(“My God”)
5. Next i
Line 1: Loop starts value from 1
Line 2: Loop will end when it reach 5
Line 3: Assign the starting value to” i” and inform to stop when the “I” reach endingValalue(5)
Line 4: Execute the loop of the body
Line 5: Taking next step , if the counter not reach the endingValalue
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim a As Integer
Dim b As Integer
a = 1
b = 5
For i = a To b
MsgBox("Message Box Shows " & var & " Times ")
Next i
End Sub
End Class
When you execute this program , It will show messagebox five time and each time it shows the counter value.
If you want to Exit from FOR Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop of the body.
Syntax:
For Countervariable=[starting Value] To [ending Value] [Step]
[ loop of the Body ]
Condition
[ Exit For ]
Next [ countervariable ]
Example for EXIT For Loop
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim a As Integer
Dim b As Integer
a = 1
b = 5
For i = a To b
MsgBox("Message Box Shows " & var & " Times ")
If i=3 Then
Exit For
End If
Next i
End Sub
End Class