keepcalculator

06 Numbers and Powers

User Defined Function VBA: How to Create & Use

Card No. 06·49597 · Updated · Standard formula, shown below

Custom power 25.00
Number
5
You entered
Power
2
You entered
You enter
Number, Power
You get
Custom power
Rounding
2 dp

A user defined function (UDF) in VBA is a custom function you write in the Visual Basic for Applications editor to perform calculations or actions that Excel’s built-in functions cannot do directly. You enter the function’s code once, then call it in a worksheet cell just like SUM or VLOOKUP, passing in your own arguments and receiving a single value back. This article explains how UDFs work, how to write your first one, common pitfalls, and when they are the right tool compared to macros or lambdas.

What Is a User Defined Function in VBA?

A UDF is a Function procedure stored in a standard module (or a class module) in the VBA project. Unlike a Sub macro, a function returns a value and can be used directly in a worksheet formula. For example, you could write a function that converts a temperature from Celsius to Fahrenheit, calculates the area of a triangle, or extracts the domain from an email address. The function accepts inputs (arguments) and returns a result of a declared data type (such as Double, String, or Boolean).

UDFs are stored in the workbook or an add-in, and they appear in the Insert Function dialog under the “User Defined” category. They are recalculated when any of their input cells change, just like native Excel functions, provided the workbook is set to automatic calculation.

How to Create a UDF in VBA

Creating a UDF involves opening the VBA editor, inserting a module, and writing the function code. Here are the steps:

  1. Press Alt+F11 to open the VBA editor.
  2. In the Project Explorer, right-click any workbook name, choose Insert > Module.
  3. In the new module’s code window, type Function MyFunction(...) and press Enter. VBA automatically adds End Function.
  4. Write the code that computes the result and assign it to the function name. For example:
Function CelsiusToFahrenheit(celsius As Double) As Double
    CelsiusToFahrenheit = celsius * 9 / 5 + 32
End Function

After writing the code, close the editor and use the function in a cell: =CelsiusToFahrenheit(20) returns 68. You can also reference a cell: =CelsiusToFahrenheit(A1).

Important: the function name must not contain spaces or conflict with a built-in function name. The function must be in a module, not in a worksheet’s code pane, to be callable from a cell.

UDF Arguments and Data Types

UDFs can accept zero or more arguments, each with a declared data type. Common types include Double (decimal numbers), Long (whole numbers), String (text), Boolean (True/False), and Range (a cell or range reference). Using a Range argument lets you pass a cell reference and read its value inside the function. For example:

Function SquareOfCell(rng As Range) As Double
    SquareOfCell = rng.Value ^ 2
End Function

You can also make arguments optional by adding Optional before the declaration and providing a default value. Optional arguments must come after all required arguments. For instance:

Function Greet(name As String, Optional prefix As String = "Hello") As String
    Greet = prefix & ", " & name
End Function

When calling =Greet("Ana"), the result is “Hello, Ana”. If you supply a second argument, it overrides the default.

How to Call a UDF in a Worksheet

Once the function is saved, you can use it in a cell in two ways:

  • Type the formula directly, e.g., =CelsiusToFahrenheit(A1).
  • Use the Insert Function dialog (fx button), select “User Defined” category, and pick your function.

UDFs behave like native functions in most respects: they appear in the formula bar, can be used in conditional formatting, and are recalculated when inputs change. However, they do not show a tooltip with argument descriptions unless you add a Description property via the MacroOptions method (in Excel 2010 and later).

One key difference: a UDF cannot change the structure of the worksheet (insert rows, format cells, etc.) when called from a cell. It can only return a value. If you need to modify the sheet, you must use a Sub macro.

Common Errors and Debugging Tips

When writing UDFs, you may encounter a few common issues:

  • #NAME? error – The function name is misspelled or the module is not in the same workbook. Check the spelling and ensure the function is in a standard module.
  • #VALUE! error – The function returned a value that Excel cannot display, or an argument is of the wrong type. For example, passing text to a Double argument causes this error.
  • Volatile functions not updating – By default, a UDF recalculates only when its input cells change. If the function depends on something else (like the current time or a cell outside the argument list), you may need to declare it volatile using Application.Volatile at the start of the function.
  • Slow performance – UDFs that loop through large ranges can be slow. Minimize range access by reading values into an array first, and avoid using Select or Activate inside a function.

To debug, place a breakpoint (F9) inside the function and then enter the formula in a cell. The code will pause, and you can step through with F8. Also check the Immediate Window (Ctrl+G) for Debug.Print output.

UDF vs. Sub Macro vs. Lambda

Understanding the difference between a UDF and a Sub macro is crucial. A Sub macro performs actions (like formatting, copying, or creating charts) but does not return a value to a cell. A UDF returns a value but cannot change the worksheet’s structure. If you need both, you can have a Sub call a UDF to compute a value and then use that value in the macro’s actions.

Excel’s LAMBDA function (introduced in Excel 365) allows you to create custom functions without VBA, using formula syntax only. LAMBDA is easier for simple calculations and works across platforms (Windows, Mac, web). However, VBA UDFs are still necessary for complex logic, accessing external data, or using Windows API calls. For example, a UDF can read a file, query a database, or interact with another application—something LAMBDA cannot do directly.

Choose a UDF when you need to reuse a calculation that is too complex for a single formula, when you need to interact with other Office applications, or when you need to use VBA features like arrays, loops, or error handling. Choose LAMBDA for simpler, portable calculations that don’t require VBA.

Security and Sharing Workbooks with UDFs

UDFs are stored in the workbook’s VBA project, which may contain macros. When you share a workbook with UDFs, the recipient must enable macros (or trust the file) for the functions to work. In Excel, you can set the macro security level to “Disable all macros with notification” so the user can choose to enable them. If the workbook is saved as .xlsx (without macros), the UDF code is lost. Save as .xlsm (macro-enabled) or .xlam (add-in) to preserve the code.

Be cautious when opening workbooks from untrusted sources, as VBA code can contain harmful instructions. Only enable macros if you trust the source. Also, if you plan to distribute a UDF widely, consider creating an add-in (.xlam) and installing it via Excel’s Add-Ins dialog. This makes the function available in all workbooks on that machine.

Frequently Asked Questions

How do I create a user defined function in Excel?

Open the VBA editor (Alt+F11), insert a new module, and type Function FunctionName(...) followed by the code that assigns a value to the function name. Close the editor and use the function in a cell like any built-in function.

Why is my UDF not showing in the formula list?

Make sure the function is in a standard module (not a sheet module) and that the workbook is macro-enabled (.xlsm). Also, check that the function name does not conflict with a built-in name. If you want it to appear in the Insert Function dialog, you may need to add a description using Application.MacroOptions.

Can a UDF change cell formatting?

No, when called from a worksheet cell, a UDF can only return a value. It cannot format cells, insert rows, or perform other actions that modify the worksheet. To do that, use a Sub macro.

How do I make a UDF recalculate when any cell changes?

Add Application.Volatile at the beginning of the function code. This forces Excel to recalculate the function every time the worksheet recalculates, even if its input cells haven’t changed. Use this sparingly because it can slow down large workbooks.

Can I use a UDF in conditional formatting?

Yes, you can reference a UDF in a conditional formatting rule, but the function must return a Boolean (True/False) or a number that can be evaluated as a condition. Note that volatile UDFs may cause performance issues in large sheets.

What is the difference between a UDF and a macro?

A macro is a Sub procedure that performs actions on the workbook, such as formatting or data manipulation. A UDF is a Function procedure that returns a value and is used in formulas. Macros can call UDFs, but UDFs cannot perform actions that modify the worksheet structure.

Related

Formula used
in x | Number | - | 5 | -1000000 | 1000000
in y | Power | - | 2 | 0 | 10
out result | Custom power | - | x ^ y | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →