How to use FOR NEXT loop in

Whenever you face a situation in programming to repeat a task for several times (more than one times ) or you have to repeat a task till you reach a condtition, in these situations you can use loop statements to achieve your desired results. This kind of for loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate.


The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to a fixed number of times.

  1. var : The counter for the loop to repeat the steps.
  2. starValue : The starting value assign to counter variable.
  3. endValue : When the counter variable reach end value the Loop will stop.
  4. loopBody : 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.

  1. Line 1: Loop starts value from 1.
  2. Line 2: Loop will end when it reach 5.
  3. Line 3: Assign the starting value to var and inform to stop when the var reach endVal.
  4. Line 4: Execute the loop body.
  5. Line 5: Taking next step , if the counter not reach the endVal.

VB.NET Source Code

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 NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, 
	ByVal e As System.EventArgs) Handles Button1.Click
        Dim var As Integer
        Dim startVal As Integer
        Dim endVal As Integer
        startVal = 1
        endVal = 5
        For var = startVal To endVal
            MsgBox("Message Box Shows "  var   " Times ")
            If var = 3 Then
                Exit For
            End If
        Next var
    End Sub
End Class

When you execute the above source code , the program shows the message box only three times . (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About