Lesson 17: Creating User-Defined Functions in VB2022

Master the art of creating reusable functions that return values

Key Takeaway

Functions are reusable code blocks that perform calculations and return values. They help organize code, reduce duplication, and make programs easier to maintain.

Welcome to Lesson 17 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to create custom functions that return values. Functions are essential building blocks that help you write clean, modular, and reusable code.

Learning Objectives

  • Understand the structure and purpose of functions
  • Create functions with different return types
  • Pass parameters to functions effectively
  • Understand the difference between ByVal and ByRef
  • Implement functions for common programming tasks
  • Apply best practices for organizing code with functions
  • Create reusable components that return values

17.1 Function Fundamentals

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

Function Execution Flow

Main Program Call Function Execute Function Return Value to Main

17.1.1 Function Structure

The basic syntax of a function:

FunctionSyntax.vb
[AccessModifier] Function FunctionName([parameters]) As ReturnType
    ' Statements to perform the task
    Return value  ' Or assign to function name
End Function
Component Description Example
Access Modifier Defines visibility (Public, Private, Protected) Private, Public
Function Keyword Indicates a function Function
Function Name Descriptive name following naming conventions CalculateBMI
Parameters Optional data passed to the function (height As Single, weight As Single)
Return Type Data type of the returned value Double, String, Boolean

Best Practice

Use descriptive names for your functions that clearly indicate their purpose and return value. For example, "CalculateTotal" is better than "GetResult".

17.2 Creating and Using Functions

Functions can be called from anywhere in your code, making them reusable components that return values.

17.2.1 Basic Function Examples

1 BMI Calculator

Create a function to calculate Body Mass Index:

BMICalculator.vb
Private Function CalculateBMI(height As Single, weight As Single) As Double
    Return weight / (height * height)
End Function

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim h As Single = Val(txtHeight.Text)
    Dim w As Single = Val(txtWeight.Text)
    
    Dim bmi As Double = CalculateBMI(h, w)
    lblResult.Text = "Your BMI is: " & Math.Round(bmi, 2)
End Sub

Output Preview

Height: 1.75

Weight: 68

Your BMI is: 22.2

2 Future Value Calculator

Calculate future value of an investment:

FutureValue.vb
Private Function CalculateFutureValue(pv As Double, rate As Double, periods As Integer) As Double
    Return pv * Math.Pow(1 + rate / 100, periods)
End Function

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim presentVal As Double = Val(txtPresent.Text)
    Dim interestRate As Double = Val(txtRate.Text)
    Dim years As Integer = Val(txtYears.Text)
    
    Dim futureVal As Double = CalculateFutureValue(presentVal, interestRate, years)
    lblResult.Text = "Future Value: $" & futureVal.ToString("#,##0.00")
End Sub

17.3 Parameter Passing Techniques

Parameters allow you to pass data to functions. 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

17.3.1 ByVal vs ByRef Examples

1 ByVal Example

Passing parameters by value:

ByValExample.vb
Private Function Square(ByVal num As Integer) As Integer
    num = num * num  ' Changes local copy
    Return num
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim value As Integer = 5
    Dim result As Integer = Square(value)
    
    MessageBox.Show("Result: " & result)  ' Shows 25
    MessageBox.Show("Original Value: " & value)  ' Still 5
End Sub

2 ByRef Example

Passing parameters by reference:

ByRefExample.vb
Private Function Square(ByRef num As Integer) As Integer
    num = num * num  ' Changes original variable
    Return num
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim value As Integer = 5
    Dim result As Integer = Square(value)
    
    MessageBox.Show("Result: " & result)  ' Shows 25
    MessageBox.Show("Original Value: " & value)  ' Now 25
End Sub

17.4 Advanced Function Techniques

More powerful ways to use functions in your applications.

1 Prime Number Checker

Create a function to check if a number is prime:

PrimeChecker.vb
Private Function IsPrime(num As Integer) As Boolean
    If num < 2 Then Return False
    If num = 2 Then Return True
    If num Mod 2 = 0 Then Return False
    
    Dim limit As Integer = Math.Sqrt(num)
    For i As Integer = 3 To limit Step 2
        If num Mod i = 0 Then Return False
    Next
    Return True
End Function

Private Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
    Dim number As Integer
    If Integer.TryParse(txtNumber.Text, number) Then
        If IsPrime(number) Then
            lblResult.Text = number & " is a prime number"
        Else
            lblResult.Text = number & " is NOT a prime number"
        End If
    Else
        MessageBox.Show("Please enter a valid integer")
    End If
End Sub

Output Preview

Enter number: 17

17 is a prime number

2 Temperature Converter

Create reusable conversion functions:

TemperatureConverter.vb
Private Function CelsiusToFahrenheit(c As Double) As Double
    Return (c * 9 / 5) + 32
End Function

Private Function FahrenheitToCelsius(f As Double) As Double
    Return (f - 32) * 5 / 9
End Function

Private Sub btnConvertCtoF_Click(sender As Object, e As EventArgs) Handles btnConvertCtoF.Click
    Dim celsius As Double
    If Double.TryParse(txtCelsius.Text, celsius) Then
        txtFahrenheit.Text = CelsiusToFahrenheit(celsius).ToString("0.0")
    Else
        MessageBox.Show("Please enter a valid number")
    End If
End Sub

3 Grade Calculator

Create a function to calculate letter grades:

GradeCalculator.vb
Private Function CalculateGrade(score As Integer) As String
    Select Case score
        Case Is >= 90 : Return "A"
        Case Is >= 80 : Return "B"
        Case Is >= 70 : Return "C"
        Case Is >= 60 : Return "D"
        Case Else : Return "F"
    End Select
End Function

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    Dim score As Integer
    If Integer.TryParse(txtScore.Text, score) Then
        If score >= 0 And score <= 100 Then
            lblGrade.Text = "Grade: " & CalculateGrade(score)
        Else
            MessageBox.Show("Score must be between 0 and 100")
        End If
    Else
        MessageBox.Show("Please enter a valid number")
    End If
End Sub

Lesson Summary

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

Structure

Defined with Function/End Function, must return a value

Reusability

Call functions 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 built-in math functions.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Area Calculator

Create a program that:

  1. Has functions to calculate area of rectangle, circle, and triangle
  2. Allows user to select shape and input dimensions
  3. Displays the calculated area

Exercise 2: Password Strength Checker

Build an application that:

  1. Uses a function to check password strength
  2. Returns strength level (Weak, Medium, Strong) based on criteria
  3. Criteria: length, uppercase, lowercase, numbers, special characters

Exercise 3: Tax Calculator

Implement a solution that:

  1. Calculates tax based on income brackets
  2. Uses a function that accepts income and returns tax amount
  3. Displays net income after tax

Next Lesson

Ready to learn about math functions? Continue to Lesson 18: Math 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