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
16.1.1 Sub Procedure Structure
The basic syntax of a sub procedure:
[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:
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
2 Password Cracker
Use a sub procedure in a password cracking simulation:
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:
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:
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:
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:
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:
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:
- Has a sub procedure called DisplayGreeting that accepts a name
- Displays a personalized greeting message
- Calls this procedure with different names from button clicks
Exercise 2: Background Toggler
Build an application that:
- Uses a sub procedure to toggle the form's background color
- Alternates between two colors each time it's called
- Add a button to trigger the color change
Exercise 3: Factorial Calculator
Implement a solution that:
- Calculates factorial using a recursive sub procedure
- Displays the result for numbers entered by the user
- Handles edge cases (0! = 1, negative numbers)
Next Lesson
Ready to learn about functions? Continue to Lesson 17: Creating Functions in VB2022.
Related Resources

Visual Basic 2022 Made Easy
The ultimate beginner-friendly guide for mastering Windows-based application development using Visual Basic in Visual Studio 2022. Whether you're a student, teacher, hobbyist, or self-learner, this book offers a clear, step-by-step approach to help you get started with ease.
What You'll Learn:
- Control structures and procedures
- Decision-making techniques
- Efficient code organization
- Practical application development
- Best practices in VB2022

Mastering Excel VBA 365
Your ultimate step-by-step guide to automating tasks, building macros, and creating powerful applications within Microsoft Excel 365. Whether you're a student, business professional, or aspiring programmer, this comprehensive handbook will help you unlock the full potential of Excel's VBA.
What You'll Learn:
- Control structures in VBA
- Decision-making techniques
- Data processing and analysis
- Report generation
- Automated workflows