Skip to Content
Course content

5.4 Returning Values with Functions.

In VBA, Functions are used when you need to return a value after performing some operations or calculations. Functions are similar to Subroutines (Subs), but while Subs perform an action without returning a value, Functions are designed to return a result to the calling procedure or code. This makes Functions ideal for situations where you need to calculate or process data and then return the result for further use.

1. Declaring a Function

A Function is declared with the Function keyword followed by the function name, any parameters (optional), and the return type. The value returned by the function is assigned to the function name itself.

Basic Syntax to Declare a Function:

Function FunctionName(Param1 As DataType, Param2 As DataType) As DataType
    ' Code to perform operations
    FunctionName = result  ' Assign the result to the function name
End Function
  • FunctionName: The name of the function.
  • Parameters: The inputs to the function (optional).
  • Return Type: The data type of the value that the function will return.
  • result: The computed result that the function will return.

2. Example of a Simple Function

Let’s consider a simple example where a function returns the sum of two numbers.

Example 1: A Basic Function

Function AddNumbers(a As Double, b As Double) As Double
    AddNumbers = a + b  ' Return the sum of a and b
End Function

In this example, the AddNumbers function accepts two arguments (a and b) and returns their sum as a Double.

Calling the Function:

To call the function and store the result, use the function name like this:

Sub Test()
    Dim result As Double
    result = AddNumbers(5, 10)  ' Call the AddNumbers function
    MsgBox "The sum is: " & result
End Sub

This will display a message box with the sum of 5 and 10.

3. Returning Values with Functions

The key concept in a function is that the result of the function is returned to the calling code. To do this, you assign the result of the calculation or operation to the function name itself.

Syntax to Return a Value:

Function FunctionName() As DataType
    FunctionName = result  ' Assign the return value to the function name
End Function

Example of a Function Returning a Value:

Function MultiplyNumbers(a As Double, b As Double) As Double
    MultiplyNumbers = a * b  ' Return the product of a and b
End Function

Here, the function MultiplyNumbers returns the product of the numbers passed as arguments.

Calling the Function:

Sub Test()
    Dim product As Double
    product = MultiplyNumbers(4, 5)  ' Calling the function
    MsgBox "The product is: " & product
End Sub

This will display a message box with the product of 4 and 5.

4. Returning Values from Functions with Different Data Types

Functions can return different data types such as integers, doubles, strings, booleans, or even more complex objects.

Example 1: Function Returning a String

Function GreetUser(name As String) As String
    GreetUser = "Hello, " & name  ' Return a greeting message
End Function

Calling the Function:

Sub TestGreeting()
    Dim greeting As String
    greeting = GreetUser("John")  ' Call the GreetUser function
    MsgBox greeting  ' Display the greeting
End Sub

This will display "Hello, John" in a message box.

Example 2: Function Returning a Boolean

Function IsEvenNumber(n As Integer) As Boolean
    If n Mod 2 = 0 Then
        IsEvenNumber = True  ' Return True if the number is even
    Else
        IsEvenNumber = False  ' Return False if the number is odd
    End If
End Function

Calling the Function:

Sub TestIsEven()
    If IsEvenNumber(10) Then
        MsgBox "10 is an even number"
    Else
        MsgBox "10 is not an even number"
    End If
End Sub

This will display "10 is an even number" in a message box.

5. Returning Multiple Values

A function can only return one value at a time. However, if you need to return multiple values, you can use arrays, user-defined types (UDTs), or pass arguments by reference.

Example Using an Array:

Function GetRangeData() As Variant
    Dim data(1 To 3) As Double
    data(1) = 10
    data(2) = 20
    data(3) = 30
    GetRangeData = data  ' Return the array
End Function

Calling the Function:

Sub TestArrayReturn()
    Dim result As Variant
    result = GetRangeData()
    MsgBox "First value: " & result(1)  ' Display the first element of the array
End Sub

In this case, the GetRangeData function returns an array, and the calling procedure can access individual elements of that array.

6. Best Practices for Returning Values

  • Use Functions for Calculations: Whenever you need to perform a calculation or logic and return a result, functions are the most appropriate solution.
  • Keep Functions Focused: A function should ideally do one thing and return a result related to that action. This makes it easier to maintain and reuse.
  • Return Appropriate Data Types: Make sure that the function returns the correct data type as specified in the function declaration. For example, if the function is supposed to return a Double, it should always return a Double.
  • Use Functions in Formulas: VBA functions can also be used in Excel formulas, making them even more useful. For instance, you could create custom functions that can be called directly from a worksheet cell.

7. Summary

  • Functions are used to perform a task and return a value, making them different from subroutines, which perform actions but do not return values.
  • You return a value in a function by assigning it to the function name.
  • Functions can return various data types, including numbers, strings, booleans, and arrays.
  • Use Functions when you need to calculate, process, or retrieve a result and send that result back to the caller.

By understanding how to declare, use, and return values in functions, you can structure your VBA code more effectively and create reusable, modular code that simplifies your projects.

Commenting is not enabled on this course.