Lesson 16: Mastering Sub Procedures in VB2022

Organizing code into reusable blocks for efficient programming

Key Takeaway

Sub procedures are fundamental building blocks in VB2022 that allow you to organize code into reusable, manageable segments that perform specific tasks without returning values.

Welcome to Lesson 16 of our Visual Basic 2022 Tutorial! In this lesson, you'll master the art of organizing your code using sub procedures. You'll learn how to create modular, reusable code blocks that enhance readability, maintainability, and efficiency in your applications.

Learning Objectives

  • Understand the structure and purpose of sub procedures
  • Create sub procedures with and without parameters
  • Call sub procedures from different parts of your code
  • Pass parameters by value and by reference
  • Implement sub procedures for common programming tasks
  • Apply best practices for organizing code with sub procedures
  • Create reusable components for your applications

16.1 Sub Procedure Fundamentals

Sub procedures are self-contained blocks of code that perform specific tasks. They help organize your code into logical units and promote code reuse.

Sub Procedure Execution Flow

Main Program Call Sub Procedure Execute Sub Procedure Return to Main Program

16.1.1 Sub Procedure Structure

The basic syntax of a sub procedure:

SubProcedureSyntax.vb
[AccessModifier] Sub ProcedureName([parameters])
    ' Statements to perform the task
End Sub
Component Description Example
Access Modifier Defines visibility (Public, Private, Protected) Private, Public
Sub Keyword Indicates a sub procedure Sub
Procedure Name Descriptive name following naming conventions CalculateSum
Parameters Optional data passed to the procedure (a As Integer, b As Integer)

Best Practice

Use descriptive names for your sub procedures that clearly indicate their purpose. For example, "CalculateTotal" is better than "DoCalc".

16.2 Creating and Calling Sub Procedures

Sub procedures can be called from anywhere in your code, making them reusable components.

16.2.1 Basic Sub Procedure Example

1 Simple Addition

Create a sub procedure to add two numbers:

SimpleAddition.vb
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Call the sub procedure with two numbers
    Sum(5, 6)
End Sub

' Define the sum sub procedure
Sub Sum(a As Single, b As Single)
    ' Display the result in a message box
    MsgBox("The sum is: " & (a + b))
End Sub

Output Preview

The sum is: 11

2 Password Cracker

Use a sub procedure in a password cracking simulation:

PasswordCracker.vb
Public Class Form1
    Dim password As Integer
    Dim crackpass As Integer
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' Start the password generation process
        Timer1.Enabled = True
    End Sub
    
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        ' Generate a new password attempt
        GeneratePassword()
        
        ' Check if password is found
        If crackpass = password Then
            Timer1.Enabled = False
            Label1.Text = crackpass
            MsgBox("Password Cracked! Login Successful!")
        Else
            Label1.Text = crackpass
            Label2.Text = "Please wait..."
        End If
    End Sub
    
    ' Sub procedure to generate password attempts
    Sub GeneratePassword()
        ' Generate a random number between 100 and 199
        crackpass = Int(Rnd() * 100) + 100
    End Sub
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Set the actual password
        password = 123
    End Sub 
End Class

16.3 Parameter Passing Techniques

Parameters allow you to pass data to sub procedures. VB2022 supports two parameter passing mechanisms:

Method Keyword Behavior Use Case
By Value ByVal Passes a copy of the variable When original value shouldn't be modified
By Reference ByRef Passes a reference to the variable When original value needs modification

16.3.1 ByVal vs ByRef Examples

1 ByVal Example

Passing parameters by value:

ByValExample.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim num As Integer = 5
    ModifyValue(num)
    MessageBox.Show("Original value: " & num) ' Output: 5
End Sub

Sub ModifyValue(ByVal value As Integer)
    value = 10
End Sub

2 ByRef Example

Passing parameters by reference:

ByRefExample.vb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim num As Integer = 5
    ModifyReference(num)
    MessageBox.Show("Modified value: " & num) ' Output: 10
End Sub

Sub ModifyReference(ByRef value As Integer)
    value = 10
End Sub

16.4 Advanced Sub Procedure Techniques

More powerful ways to use sub procedures in your applications.

1 Data Validation

Create reusable validation procedures:

DataValidation.vb
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    If Not ValidateEmail(txtEmail.Text) Then
        MsgBox("Please enter a valid email address")
        Return
    End If
    
    If Not ValidateAge(txtAge.Text) Then
        MsgBox("Please enter a valid age (18-99)")
        Return
    End If
    
    ProcessRegistration()
End Sub

' Email validation procedure
Function ValidateEmail(email As String) As Boolean
    Return email.Contains("@") And email.Contains(".")
End Function

' Age validation procedure
Function ValidateAge(ageText As String) As Boolean
    Dim age As Integer
    Return Integer.TryParse(ageText, age) AndAlso age >= 18 AndAlso age <= 99
End Function

' Registration processing
Sub ProcessRegistration()
    ' Code to process registration
    MsgBox("Registration successful!")
End Sub

2 Temperature Conversion

Create reusable conversion procedures:

TemperatureConversion.vb
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
    Dim celsius As Double
    Dim fahrenheit As Double
    
    If Not Double.TryParse(txtCelsius.Text, celsius) Then
        MsgBox("Please enter a valid number")
        Return
    End If
    
    ' Convert to Fahrenheit
    CelsiusToFahrenheit(celsius, fahrenheit)
    lblFahrenheit.Text = fahrenheit.ToString("F1")
End Sub

' Conversion procedure
Sub CelsiusToFahrenheit(ByVal c As Double, ByRef f As Double)
    f = (c * 9 / 5) + 32
End Sub

3 Drawing Shapes

Create procedures to draw different shapes:

ShapeDrawing.vb
Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
    Dim g As Graphics = PictureBox1.CreateGraphics()
    
    ' Clear the picture box
    g.Clear(Color.White)
    
    ' Draw different shapes
    DrawCircle(g, 50, 50, 40, Color.Red)
    DrawRectangle(g, 150, 50, 80, 60, Color.Blue)
    DrawTriangle(g, 300, 50, 60, Color.Green)
End Sub

' Circle drawing procedure
Sub DrawCircle(g As Graphics, x As Integer, y As Integer, diameter As Integer, color As Color)
    Dim pen As New Pen(color, 3)
    g.DrawEllipse(pen, x, y, diameter, diameter)
End Sub

' Rectangle drawing procedure
Sub DrawRectangle(g As Graphics, x As Integer, y As Integer, width As Integer, height As Integer, color As Color)
    Dim pen As New Pen(color, 3)
    g.DrawRectangle(pen, x, y, width, height)
End Sub

' Triangle drawing procedure
Sub DrawTriangle(g As Graphics, x As Integer, y As Integer, size As Integer, color As Color)
    Dim pen As New Pen(color, 3)
    Dim points() As Point = {
        New Point(x, y + size),
        New Point(x + size / 2, y),
        New Point(x + size, y + size)
    }
    g.DrawPolygon(pen, points)
End Sub

Lesson Summary

In this lesson, we've covered essential concepts about sub procedures in VB2022:

Structure

Defined with Sub/End Sub, can include parameters

Reusability

Call procedures multiple times from different locations

Parameters

Pass data using ByVal (value) or ByRef (reference)

Organization

Break complex code into manageable units

Maintenance

Easier to debug and update modular code

These skills will help you create more organized and maintainable applications. In the next lesson, we'll explore functions that return values.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Greeting Generator

Create a program that:

  1. Has a sub procedure called DisplayGreeting that accepts a name
  2. Displays a personalized greeting message
  3. Calls this procedure with different names from button clicks

Exercise 2: Background Toggler

Build an application that:

  1. Uses a sub procedure to toggle the form's background color
  2. Alternates between two colors each time it's called
  3. Add a button to trigger the color change

Exercise 3: Factorial Calculator

Implement a solution that:

  1. Calculates factorial using a recursive sub procedure
  2. Displays the result for numbers entered by the user
  3. Handles edge cases (0! = 1, negative numbers)

Next Lesson

Ready to learn about functions? Continue to Lesson 17: Creating Functions in VB2022.

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