Understanding VBA Functions and Subroutines in Excel

In Excel VBA, functions and subroutines are essential tools for automating tasks and processing data. Let’s explore the key differences between these two constructs and see how they can be used effectively to streamline your VBA code.

Function

A function in Excel VBA is a versatile tool that performs a task and returns a value. It’s perfect for situations where you need a specific result. Here’s how to create a function:

  1. Open the Visual Basic Editor by clicking Insert > Module.
  2. Define your function, giving it a name and specifying its arguments and return type. For example:
Function Area(x As Double, y As Double) As Double
    Area = x * y
End Function

  1. You can now use this function in your code to calculate values. For example:
Dim z As Double
z = Area(3, 5) + 2
MsgBox z

Result: When you click the command button, it displays the result “17” in a message box.

Excel VBA Function Result

Subroutine (Sub)

A subroutine in Excel VBA is designed for performing actions without returning a value. Here’s how to create a subroutine:

  1. Open the Visual Basic Editor by clicking Insert > Module.
  2. Define your subroutine, specifying its arguments. For example:
Sub Area(x As Double, y As Double)
    MsgBox x * y
End Sub

  1. You can call this subroutine from your code to perform actions. For example:
Area 3, 5

Result: Click the command button to see a message box displaying the result “15”. Subroutines don’t return values.

Excel VBA Sub Result

User Defined Function (UDF)

User Defined Functions (UDFs) are custom functions you can create in Excel VBA. They are particularly useful when built-in Excel functions aren’t sufficient. Let’s create a UDF called SUMEVENNUMBERS to sum even numbers in a given range.

  1. Open the Visual Basic Editor by clicking Insert > Module.
  2. Define the UDF, specifying its arguments. For example:
Function SUMEVENNUMBERS(rng As Range) As Double

User Defined Function in Excel VBA
  1. Within the UDF, declare variables and set up a loop to check each cell in the provided range.
Dim cell As Range
For Each cell In rng

  1. Calculate the sum of even numbers and the count of even numbers in the range.
    If cell.Value Mod 2 = 0 Then
        SUMEVENNUMBERS = SUMEVENNUMBERS + cell.Value
    End If
Next cell

  1. End the UDF.
End Function

  1. You can now use this custom function in Excel, just like any other function, to find the sum of even numbers in a range.
User Defined Function Result

Custom Average Function

Let’s create another UDF, a custom average function that calculates the average of values in a range, excluding outliers.

  1. Open the Visual Basic Editor by clicking Insert > Module.
  2. Define the UDF, specifying its arguments. For example:
Function CUSTOMAVERAGE(rng As Range, lower As Integer, upper As Integer) As Double

Custom Average Function in Excel VBA
  1. Declare variables and set up a loop to check each cell in the provided range.
Dim cell As Range, total As Integer, count As Integer
For Each cell In rng

  1. Calculate the average by excluding values outside the specified range.
    If cell.Value >= lower And cell.Value <= upper Then
        total = total + cell.Value
        count = count + 1
    End If
Next cell

  1. Calculate the custom average and end the UDF.
CUSTOMAVERAGE = total / count
End Function

  1. You can use this custom average function to calculate averages, excluding specified outliers.
Custom Average Function Check

Volatile Functions

By default, UDFs in Excel VBA are not volatile. They recalculate only when one of their arguments changes. If you need a function to recalculate every time any cell on the worksheet is recalculated, you can make it volatile.

To make a UDF volatile, you can use the Application.Volatile statement within the UDF.

ByRef and ByVal

In Excel VBA, you can pass arguments to a procedure (function or sub) by reference (ByRef) or by value (ByVal). By default, VBA passes arguments by reference.

Here’s an example to illustrate the difference between ByRef and ByVal:

Dim x As Integer
x = 10

MsgBox Triple(x)
MsgBox x

In the module:

Function Triple(ByRef x As Integer) As Integer
    x = x * 3
    Triple = x
End Function

Result: The second MsgBox" displays a value of 30 because the original value of x"was changed within the function.

ByRef Result

To pass arguments by value, modify the function like this:

Function Triple(ByVal x As Integer) As Integer
    x = x * 3
    Triple = x
End Function

ByVal Result

Result: The second MsgBox" displays a value of 10 because the original value of x" remains unchanged.

Understanding how to use functions, subroutines, UDFs, and arguments passed by reference or by value is crucial for efficient VBA programming in Excel.

Functions vs. Formulas: Unveiling the Key Differences

Formulas and functions are essential tools in Excel, empowering users to perform calculations ranging from simple to complex. While both serve mathematical purposes, they differ significantly in their nature and application.

Key Distinctions Between Formulas and Functions

  1. Customization: A formula in Excel is a user-defined statement capable of incorporating a wide range of operations, tailored to specific calculation needs. In contrast, a function is a predefined operation provided by Excel, limiting customization to the available parameters.
  2. Scope: Formulas can operate within a single cell or across a range of cells, facilitating intricate calculations. Functions, on the other hand, are designed for quick and common tasks like finding minimum or maximum values, averages, and more.
  3. Modification: Functions can be adjusted as needed by developers, altering their parameters to suit different scenarios. Formulas, however, lack this flexibility and are used only when explicitly needed.
  4. Interchangeability: Functions can be used within formulas, but formulas cannot be used as functions. This distinction underscores the versatility of functions for complex calculations.
  5. Usability: While formulas can handle simple manual calculations, functions excel in tackling complex operations efficiently. Functions come with predefined syntax, making them more structured and accessible for users.
  6. Parameters: Functions are equipped with predefined parameters that dictate their behavior. Formulas lack these built-in parameters and require manual specification.

Examples of Formulas

To create a formula in Excel, users initiate it with an equal sign. Here are some examples:

=4+13

=A3+C19

=B77+B8-(4*2)+

Examples of Functions

Functions are invoked by typing an equal sign followed by a predefined set of letters or by using the function wizard (Fx button in the formula bar). Some examples include:

=SUM(A2:A27)

=AVERAGE(F2:F8)

=NPV(0.10, A5:G5)

Combining Formulas and Functions

Users can harness the combined power of formulas and functions to perform intricate analyses. Examples of such combinations include:

=SUM(A4:A8)/5

=AVERAGE(B4:B19) + 24 + SUM(1,2,3,5)

=NPV(0.10, A5:G5) * 0.8

From a communication and comprehension perspective, there isn’t a substantial difference between formulas and functions. However, it’s important to recognize that functions are predefined, code-like operations, while formulas are user-crafted statements. Both are indispensable tools for data analysis and calculations in Excel.