Skip to content
Visual Basic

Loops and Iteration

For, For Each, While, and Do loops in VB.

By EZ4Code Team
loopiteration

Code

' For loop
For i As Integer = 1 To 10 Step 2
    Console.WriteLine(i)  ' 1, 3, 5, 7, 9
Next

' For Each
Dim names() As String = {"Alice", "Bob", "Carol"}
For Each name As String In names
    Console.WriteLine(name)
Next

' While
Dim n As Integer = 0
While n < 5
    n += 1
End While

' Do While / Until
Do
    n -= 1
Loop While n > 0

Do Until n = 0
    n -= 1
Loop

' Exit / Continue
For i = 1 To 100
    If i = 10 Then Exit For
    If i Mod 2 = 0 Then Continue For
Next

Explanation

VB's For uses To/Step (inclusive). For Each iterates IEnumerable. While checks before; Do can check before or after (Loop While/Until). Exit For breaks; Continue For skips. Do Until loops while condition is false (opposite of Do While).

More Visual Basic Snippets