Lesson 15: Looping in VB2019

Master repetitive execution with efficient loop structures

Key Takeaway

Looping allows you to execute code repeatedly, enabling efficient processing of repetitive tasks and data sets.

In this lesson, we'll explore looping structures in Visual Basic 2019. Loops are essential for executing code repeatedly without writing redundant statements, making them perfect for processing collections, generating sequences, and automating repetitive tasks.

15.1 Loop Structures

Visual Basic 2019 provides three primary looping structures: For..Next, Do..Loop, and While..End While. Each serves different purposes in controlling repetitive execution.

Loop Comparison

Loop Type Usage Best For
For..Next Fixed number of iterations Processing arrays, known ranges
Do..Loop Condition-based execution User input validation, file reading
While..End While Condition-based execution Processing until condition changes

15.1(a) For..Next Loop

The For..Next loop executes a block of code a specific number of times. It's ideal when you know exactly how many iterations you need.

For counter = start To end [Step increment]
    ' Code to execute
Next

Example 15.1: Number Sequence

This program displays numbers from 1 to 10 in a list box.

Form1.vb
Private Sub BtnGenerate_Click(sender As Object, e As EventArgs) Handles BtnGenerate.Click
    Dim counter As Integer
    
    For counter = 1 To 10
        ListBox1.Items.Add(counter)
    Next
End Sub

Output:

> Numbers 1 through 10 added to list box

Example 15.2: Step Increment

This example demonstrates using step increments to generate even numbers.

Form1.vb
Private Sub BtnEvenNumbers_Click(sender As Object, e As EventArgs) Handles BtnEvenNumbers.Click
    Dim counter As Integer
    
    For counter = 0 To 20 Step 2
        ListBox1.Items.Add(counter)
    Next
End Sub

Output:

> Even numbers: 0, 2, 4, ..., 20

15.1(b) Do Loops

Do loops execute while or until a condition is met, making them ideal for situations where the number of iterations is unknown.

Do While condition
    ' Code to execute
Loop

Example 15.3: Input Validation

This program repeatedly prompts for input until the user enters a positive number.

Form1.vb
Private Sub BtnValidate_Click(sender As Object, e As EventArgs) Handles BtnValidate.Click
    Dim userInput As Integer
    
    Do
        userInput = Val(InputBox("Enter a positive number:"))
    Loop Until userInput > 0
    
    LblResult.Text = "You entered: " & userInput
End Sub

Output:

> Prompts until positive number entered > Displays valid input

15.1(c) While..End While

The While..End While loop executes as long as a specified condition remains true.

While condition
    ' Code to execute
End While

Example 15.4: Countdown Timer

This example creates a countdown from 10 to 1.

Form1.vb
Private Sub BtnCountdown_Click(sender As Object, e As EventArgs) Handles BtnCountdown.Click
    Dim count As Integer = 10
    
    While count >= 1
        ListBox1.Items.Add(count)
        count -= 1
    End While
    
    ListBox1.Items.Add("Liftoff!")
End Sub

Output:

> 10, 9, 8, ..., 1 > "Liftoff!"
Loop example interface
Figure 15.1: Loop example interface

15.1(d) Exit Statements

Exit statements allow you to break out of loops prematurely when certain conditions are met.

Exit For - Breaks out of For loop
Exit Do - Breaks out of Do loop
Exit While - Breaks out of While loop

Example 15.5: Prime Number Check

This example checks if a number is prime using an efficient loop.

Form1.vb
Private Sub BtnCheckPrime_Click(sender As Object, e As EventArgs) Handles BtnCheckPrime.Click
    Dim num As Integer = Val(TxtNumber.Text)
    Dim isPrime As Boolean = True
    
    If num <= 1 Then
        isPrime = False
    Else
        For i = 2 To Math.Sqrt(num)
            If num Mod i = 0 Then
                isPrime = False
                Exit For
            End If
        Next
    End If
    
    If isPrime Then
        LblResult.Text = num & " is a prime number"
    Else
        LblResult.Text = num & " is not a prime number"
    End If
End Sub

Output:

> Enter 7: "7 is a prime number" > Enter 9: "9 is not a prime number"

Lesson Summary

In this lesson, you've learned how to use looping structures to execute code repeatedly in Visual Basic 2019:

For..Next Loop

Mastered fixed iteration loops with step increments

Do Loops

Learned condition-based loops for unknown iterations

While..End While

Implemented top-condition checking loops

Exit Statements

Used Exit For/Do/While to break loops early

Looping structures are fundamental for efficient programming, allowing you to process collections, validate input, and perform repetitive tasks with minimal code. In the next lesson, we'll explore sub procedures to organize and modularize your code.

Next Lesson

Ready to learn about organizing your code? Continue to Lesson 16: Sub Procedures.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More

VB2019 Paperback

Comprehensive guide to Visual Basic 2019

Get on Amazon