How to: Skip to the Next Iteration of a Loop (Visual Basic)
If you have completed your processing for the current iteration of a Do, For, or While loop, you can skip immediately to the next iteration by using a Continue Statement (Visual Basic).
Skipping to the Next Iteration
To skip to the next iteration of a For...Next loop
Write the For...Next loop in the normal way.
Use Continue For at any place you want to terminate the current iteration and proceed immediately to the next iteration.
Public Function findLargestRatio(ByVal high() As Double, ByVal low() As Double) As Double Dim ratio As Double Dim largestRatio As Double = Double.MinValue For counter As Integer = 0 To low.GetUpperBound(0) If Math.Abs(low(counter)) < System.Double.Epsilon Then Continue For ratio = high(counter) / low(counter) If Double.IsInfinity(ratio) OrElse Double.IsNaN(ratio) Then Continue For If ratio > largestRatio Then largestRatio = ratio Next counter Return largestRatio End Function
Skipping from Within a Nested Loop
If you have Do, For, or While loops nested one within another, you can skip immediately to the next iteration of any level in the nesting. This is only true, however, when the loops are of different types. If you have nested loops of the same type, for example nested While loops, Continue While skips to the next iteration of the innermost While loop.
To skip to the next iteration of a Do loop from within a nested For loop
Write the nested loops in the normal way.
Use Continue Do at any place that you want to terminate the current iteration of the inner For loop and skip to the next iteration of the outer Do loop.
Public Sub divideElements(ByRef matrix(,) As Double) Dim i As Integer = -1 Do Until i > matrix.GetUpperBound(0) i += 1 For j As Integer = 0 To matrix.GetUpperBound(1) If matrix(j, j) = 0 Then Continue Do matrix(i, j) /= matrix(j, j) Next j Loop End Sub
See Also
Tasks
How to: Transfer Control Out of a Control Structure (Visual Basic)
How to: Run Several Statements Repeatedly (Visual Basic)
How to: Run Several Statements for Each Element in a Collection or Array (Visual Basic)
How to: Improve the Performance of a Loop (Visual Basic)
Reference
While...End While Statement (Visual Basic)
Do...Loop Statement (Visual Basic)
For...Next Statement (Visual Basic)
Concepts
Loop Structures (Visual Basic)
Nested Control Structures (Visual Basic)