Exiting For Loop in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes how to exit For Next loop in Visual Basic .NET.

To leave a For loop before it would normally finish you use the Exit For statement.

For example, the following code loops through an array looking for value 10.
When it finds the element with value 10 it uses Exit For to immediately stop looping.

    Dim array() As Integer = {1, 3, 5, 7, 10, 20, 50}
    For i As Integer = 0 To array.GetUpperBound(0)
        If (array(i) = 10) Then
            'Quit the loop immediately
            Exit For
        End If
    Next               


The Exit For statement exits only the For loop immediately surrounding the statement.
If a For loop is nested within another For loop, the Exit For statement only exits the inner loop.

Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.