Excel VBA Function Tutorial: Return, Call, Examples

โšก Smart Summary

Excel VBA Function is a block of code that performs a task and returns a result to whatever called it. This page covers declaration syntax, returning a value, a worked addition example, and using a Function inside a worksheet cell.

  • ๐ŸŽฏ Definition: A Function performs a specific task and returns a single result to the calling code.
  • ๐Ÿงพ Syntax: Function name(arguments) As Type opens the block and End Function closes it.
  • โ†ฉ๏ธ Returning a Value: Assign the result to the function name, as in addNumbers = firstNumber + secondNumber.
  • ๐Ÿ”ข Return Type: Declaring As Long or As Double avoids the slower default Variant.
  • ๐Ÿ–ฑ๏ธ Calling: A command button passes two numbers and displays the returned sum in a message box.
  • ๐Ÿ“Š Worksheet Use: A Public Function in a standard module becomes a user defined formula in any cell.

Excel VBA Function

What is a Function?

A function is a piece of code that performs a specific task and returns a result. Functions are mostly used to carry out repetitive tasks such as formatting data for output, performing calculations, etc.

Suppose you are developing a program that calculates interest on a loan. You can create a function that accepts the loan amount and the payback period. The function can then use the loan amount and payback period to calculate the interest and return the value.

Why use functions

The advantages of using functions are the same as those listed for subroutines: they break a long program into manageable parts, they can be reused from anywhere in the project, and a descriptive name documents what the code does. The Excel VBA Subroutine tutorial covers those benefits in full.

Rules of naming functions

The naming rules are also identical to those for subroutines. A function name cannot contain a space, must begin with a letter or an underscore, and cannot be a reserved VBA keyword such as Function, Private, or End.

VBA Syntax for declaring Function

Private Function myFunction (ByVal arg1 As Integer, ByVal arg2 As Integer)
    myFunction = arg1 + arg2
End Function

HERE in the syntax,

Code Action
  • “Private Function myFunction(โ€ฆ)”
  • Here the keyword “Function” is used to declare a function named “myFunction” and start the body of the function.
  • The keyword ‘Private’ is used to specify the scope of the function
  • “ByVal arg1 As Integer, ByVal arg2 As Integer”
  • It declares two parameters of integer data type named ‘arg1’ and ‘arg2.’
  • myFunction = arg1 + arg2
  • evaluates the expression arg1 + arg2 and assigns the result to the name of the function.
  • “End Function”
  • “End Function” is used to end the body of the function

How to Return a Value and Set the Function Data Type

A Function has one job that a Subroutine does not: it hands a value back. Two details control that value, and both are easy to miss.

The first is the assignment. VBA has no Return statement. Instead you assign the result to the function’s own name, which is why the line reads myFunction = arg1 + arg2. If that assignment never runs, the function silently returns an empty value rather than raising an error, so every branch of the code must set it.

The second is the return type. The declaration above ends at the closing bracket, so the function returns a Variant. Adding an As clause after the brackets fixes the type, which is faster, uses less memory, and lets the compiler catch a mismatch.

Declaration Returns When to use it
Function f(x As Long) Variant Only when the result type genuinely varies
Function f(x As Long) As Long Long Whole numbers such as counts and row numbers
Function f(x As Long) As Double Double Any calculation producing decimals
Function f(x As Long) As String String Formatted text returned for display
Function f(x As Long) As Boolean Boolean A validation check answering true or false

๐Ÿ’ก Tip: Use Exit Function to leave early once the return value is set, in the same way Exit Sub leaves a subroutine.

Function demonstrated with Example:

Functions are very similar to the subroutine. The major difference between a subroutine and a function is that the function returns a value when it is called. While a subroutine does not return a value, when it is called. Let’s say you want to add two numbers. You can create a function that accepts two numbers and returns the sum of the numbers.

  1. Create the user interface
  2. Add the function
  3. Write code for the command button
  4. Test the code

Step 1) User interface

Add a command button to the worksheet as shown below

VBA Functions and Subroutine

Set the following properties of CommandButton1 to the following.

S/N Control Property Value
1 CommandButton1 Name btnAddNumbers
2 Caption Add Numbers Function

Your interface should now appear as follows

VBA Functions and Subroutine

Step 2) Function code.

  1. Press Alt + F11 to open the code window
  2. Add the following code
Private Function addNumbers(ByVal firstNumber As Integer, ByVal secondNumber As Integer)
    addNumbers = firstNumber + secondNumber
End Function

HERE in the code,

Code Action
  • “Private Function addNumbers(โ€ฆ)”
  • It declares a private function “addNumbers” that accepts two integer parameters.
  • “ByVal firstNumber As Integer, ByVal secondNumber As Integer”
  • It declares two parameter variables firstNumber and secondNumber
  • “addNumbers = firstNumber + secondNumber”
  • It adds the firstNumber and secondNumber values and assigns the sum to addNumbers.

Step 3) Write Code that calls the function

  1. Right click on the btnAddNumbers command button
  2. Select View Code
  3. Add the following code
Private Sub btnAddNumbers_Click()
    MsgBox addNumbers(2, 3)
End Sub

HERE in the code,

Code Action
“MsgBox addNumbers(2,3)”
  • It calls the function addNumbers and passes in 2 and 3 as the parameters. The function returns the sum of the two numbers five (5)

Step 4) Run the program, you will get the following results

VBA Functions and Subroutine

Download Excel containing above code

Download the above Excel Code

The button above calls the function from VBA code. A function can also be called from the worksheet itself, with no button at all.

How to Use a VBA Function in a Worksheet Cell

A function written in VBA can be typed into a cell exactly like SUM or VLOOKUP. Excel calls this a user defined function, or UDF, and it is the reason many people learn functions before subroutines. Three conditions must be met.

  • Place it in a standard module: Insert, Module in the editor. A function stored behind a worksheet or in ThisWorkbook is not visible to the formula bar.
  • Declare it Public: The example above uses Private, which hides it from Excel. Public is the default, so simply removing the keyword is enough.
  • Return a value, change nothing: A UDF cannot format cells, delete rows, or write to another cell. Excel blocks those actions and the cell shows #VALUE!.

The function below converts a temperature and can be used anywhere on the sheet.

Public Function CelsiusToF(ByVal Celsius As Double) As Double
    CelsiusToF = (Celsius * 9 / 5) + 32
End Function

Save the workbook as a macro-enabled .xlsm file, then type =CelsiusToF(A1) into any cell. The result updates whenever A1 changes, and the name appears in the formula autocomplete list under the User Defined category. Because the workbook now contains macros, anyone opening it must enable content before the formula returns a value rather than #NAME?.

Common VBA Function Errors and How to Fix Them

Four problems account for most functions that compile but return the wrong answer.

  • The function returns Empty or 0: The result was never assigned to the function name, or one branch of an If statement skips the assignment. Set the return value on every path.
  • #NAME? in a worksheet cell: The function is Private, sits in a sheet module instead of a standard module, or the workbook was saved without macros enabled.
  • Overflow with Integer arguments: The example uses As Integer, which stops at 32,767. Change both parameters and the return type to Long for any real data.
  • A changed argument surprises the caller: Omitting ByVal makes VBA pass the variable itself, so the function can alter the caller’s value. Write ByVal unless that effect is wanted.

FAQs

Not directly. Return an array or a custom Type to carry several values in one result, or declare the extra parameters ByRef so the function writes back into the caller’s variables.

Add the Optional keyword with a default, as in Optional ByVal Rate As Double = 0.05. Every parameter after an Optional one must also be Optional, and they must come last in the list.

Yes, through Application.WorksheetFunction, for example Application.WorksheetFunction.Sum(Range(“A1:A10”)). Functions that VBA already provides, such as Left or Trim, are called directly without that prefix.

Yes. Paste the worksheet formula and an AI assistant returns an equivalent Public Function with named arguments and a declared return type. Compare both results on sample rows before replacing the formula.

Yes. Supply the function and the formula, and an AI assistant points to causes such as an argument type mismatch, a missing return assignment, or an attempt to change a cell from inside a user defined function.

Summarize this post with: