VBA course · Lesson 17 of 33

User-defined functions (UDFs): your own worksheet functions

Write your own Excel functions in VBA and use them in cells like SUM: commission tiers, VAT, text clean-up, error values, spilled arrays and add-ins.

Intermediate 17 min read

Excel has around 500 built-in functions, yet sooner or later you meet a calculation that none of them does neatly: a commission scheme with five tiers, a company-specific product code check, a way to strip everything except digits from a phone number. You could build a monster formula with nested IF calls, or you can write a user-defined function (UDF) in VBA and use it in a cell exactly like SUM.

A UDF is simply a public Function in a standard module, as you learned in Functions and Subs: parameters, ByVal, ByRef and return values. Excel sees it automatically and lists it under User Defined in the Insert Function dialog.

Your first UDF

Open the VBA editor (Alt+F11, Mac: Opt+F11 or Tools > Macro > Visual Basic Editor), choose Insert > Module and type:

VBA
Option Explicit

Public Function WITHVAT(net As Double, Optional rate As Double = 0.24) As Double
    WITHVAT = Round(net * (1 + rate), 2)
End Function
A UDF that adds VAT

Now go back to a worksheet and type =WITHVAT(B2) in a cell. Excel calculates the net amount plus 24% VAT. Type =WITHVAT(B2, 13%) to use another rate. The function recalculates whenever B2 changes, just like a built-in function.

C2fx=WITHVAT(B2)
ABC
1InvoiceNetGross
2INV-20112501550
3INV-202380471.2
4INV-20399.9123.88

The UDF in action (C2 contains =WITHVAT(B2))

Result: 1550

Some rules for the code location and name:

  • The function must be in a standard module (Insert > Module). A UDF placed in a sheet module or in ThisWorkbook cannot be used in cells.
  • It must be Public (the default). A Private Function is hidden from the worksheet.
  • Avoid names that look like cell addresses. A function called TAX1 or ABC123 clashes with a cell reference and Excel returns #REF! or refuses the formula. Upper-case names are a convention that makes UDFs look like built-in functions; Excel itself is not case-sensitive.
  • Do not give a module the same name as a function inside it; the cell formula then shows #NAME?.

A tiered commission function

Here is a realistic case: sales reps earn 3% on the first 10,000 of monthly sales, 5% on the part between 10,000 and 25,000, and 7% on everything above. As a formula this is long and hard to read. As a UDF it reads like the policy document:

VBA
Option Explicit

Public Function COMMISSION(sales As Double) As Double
    Const BAND1 As Double = 10000
    Const BAND2 As Double = 25000
    Dim result As Double

    If sales <= 0 Then
        COMMISSION = 0
        Exit Function
    End If

    ' Part up to 10,000 at 3%
    result = Application.WorksheetFunction.Min(sales, BAND1) * 0.03

    ' Part between 10,000 and 25,000 at 5%
    If sales > BAND1 Then
        result = result + (Application.WorksheetFunction.Min(sales, BAND2) - BAND1) * 0.05
    End If

    ' Part above 25,000 at 7%
    If sales > BAND2 Then
        result = result + (sales - BAND2) * 0.07
    End If

    COMMISSION = Round(result, 2)
End Function
Tiered commission, each band taxed at its own rate
C4fx=COMMISSION(B4)
ABC
1RepSalesCommission
2Ana8000240
3Ben18000700
4Chloe300001400
5Dimitri250001050

Commission for each rep (C4 contains =COMMISSION(B4))

Result: 1400

Check Chloe by hand: 10,000 × 3% = 300, 15,000 × 5% = 750, 5,000 × 7% = 350, total 1,400. When the policy changes, you change two constants instead of hunting through hundreds of formulas. Using Excel worksheet functions in VBA explains the WorksheetFunction.Min call.

Dimitri sits exactly on the second threshold, so he gets 300 + 750 = 1,050 and nothing at 7%.

Working with ranges and text

A UDF can accept a Range as a parameter and loop through it. This one counts how many invoices in a range are overdue (date in the past) and skips blanks:

VBA
Option Explicit

Public Function COUNTOVERDUE(dueDates As Range) As Long
    Dim c As Range
    Dim n As Long
    For Each c In dueDates.Cells
        If IsDate(c.Value) Then
            If c.Value < Date Then n = n + 1
        End If
    Next c
    COUNTOVERDUE = n
End Function
Counting past dates in a range

And a text-cleaning function that keeps only digits, handy for phone numbers or tax IDs typed in many styles:

VBA
Option Explicit

Public Function DIGITSONLY(txt As String) As String
    Dim i As Long
    Dim ch As String
    Dim out As String
    For i = 1 To Len(txt)
        ch = Mid(txt, i, 1)
        If ch Like "#" Then out = out & ch
    Next i
    DIGITSONLY = out
End Function
Keep only the digits of a text

=DIGITSONLY("+30 (210) 555-0192") returns 302105550192. The result is text, so leading zeros survive. The Like "#" test matches any single digit; see Working with text (strings) in VBA for more text tools.

Returning Excel errors

When the input makes no sense, a good UDF returns a proper Excel error such as #VALUE! instead of a misleading 0. Declare the return type as Variant and use CVErr with one of Excel's error constants:

VBA
Option Explicit

Public Function MARGINPCT(salePrice As Variant, cost As Variant) As Variant
    If Not IsNumeric(salePrice) Or Not IsNumeric(cost) Then
        MARGINPCT = CVErr(xlErrValue)       ' #VALUE!
    ElseIf salePrice = 0 Then
        MARGINPCT = CVErr(xlErrDiv0)        ' #DIV/0!
    Else
        MARGINPCT = (salePrice - cost) / salePrice
    End If
End Function
Returning #VALUE! and #DIV/0! like a built-in function

Other constants include xlErrNA (#N/A), xlErrNum (#NUM!), xlErrRef (#REF!) and xlErrName (#NAME?). Because the result is a real error value, IFERROR and ISERROR work on it.

If a UDF hits an unhandled run-time error, Excel does not show the usual VBA error box. The cell simply shows #VALUE!. That is convenient for users but makes debugging harder; set a breakpoint in the function (F9) and edit the cell to step through it (see Error handling and debugging in VBA).

What a UDF cannot do

A function called from a cell is only allowed to return a value. Excel blocks anything that would change the workbook while it is calculating. Inside a UDF used in a cell, the following are ignored or make the function fail:

  • Changing the value of another cell (Range("D1").Value = 5 does nothing).
  • Changing formats, inserting rows, adding sheets, renaming anything.
  • Selecting or activating cells and sheets.
  • Changing most Application settings.

The same function called from a Sub has no such limits, which confuses people: "it works when I run it from my macro but not in the cell". If you need side effects, use a Sub with a button or an event (Events: macros that run by themselves).

When does a UDF recalculate?

Excel recalculates a UDF when one of the cells passed as an argument changes. It does not know about cells your code reads without receiving them as arguments. If a UDF reads Range("Rates!B2") internally, changing that rate will not update the results. Two fixes:

  • Best: pass every input as an argument, e.g. =COMMISSION(B2, Rates!B2).
  • Alternatively, add Application.Volatile as the first line. The function then recalculates every time anything in the workbook recalculates. That is right for functions that depend on time or on the state of other sheets, but it slows big workbooks down, so use it sparingly.
VBA
Option Explicit

Public Function SHEETNAMEOF() As String
    Application.Volatile
    SHEETNAMEOF = Application.Caller.Parent.Name
End Function
A volatile function that returns the name of the sheet it is on

Application.Caller is the cell that contains the formula, and its Parent is the worksheet. If someone renames the sheet, the volatile function updates at the next recalculation. To force a full recalculation of everything, press Ctrl+Alt+F9.

Returning several values (spilling)

A UDF can return an array. In Microsoft 365 and Excel 2021 the result spills into neighbouring cells just like SEQUENCE or FILTER. Return a 2-D array for a block; a 1-D array spills across a row.

VBA
Option Explicit

Public Function VATBREAKDOWN(gross As Double, Optional rate As Double = 0.24) As Variant
    Dim out(1 To 3, 1 To 1) As Variant
    Dim net As Double
    net = Round(gross / (1 + rate), 2)
    out(1, 1) = net
    out(2, 1) = Round(gross - net, 2)
    out(3, 1) = gross
    VATBREAKDOWN = out
End Function
A UDF that spills the VAT breakdown of an amount into one column

Type =VATBREAKDOWN(1240) in a cell and three cells fill: 1000, 240 and 1240. In older Excel versions you would select three cells and confirm with Ctrl+Shift+Enter. If something blocks the spill area, the cell shows #SPILL!.

Helping users: descriptions in Insert Function

When someone opens the Insert Function dialog (Shift+F3), your UDF appears with "No help available". You can add a description, a category and argument descriptions with Application.MacroOptions. Run this once (for example from Workbook_Open):

VBA
Option Explicit

Sub RegisterCommission()
    Application.MacroOptions _
        Macro:="COMMISSION", _
        Description:="Tiered sales commission: 3% up to 10,000, 5% up to 25,000, 7% above.", _
        Category:="Financial", _
        ArgumentDescriptions:=Array("Monthly sales amount of the rep")
End Sub
Adding a description and argument help to a UDF

The ArgumentDescriptions argument needs Excel 2010 or later. Excel for Mac accepts MacroOptions but the Insert Function dialog shows less detail.

Sharing UDFs: add-ins

A UDF lives in the workbook that contains it. If another workbook uses it, the formula refers to the file, e.g. ='Tools.xlsm'!COMMISSION(B2), and breaks when that file is closed. For functions you want everywhere, save a workbook containing only the modules as an Excel Add-in (.xlam) and switch it on under File > Options > Add-ins > Manage Excel Add-ins > Go (Mac: Tools > Excel Add-ins). Functions in a loaded add-in can be used in any workbook without a file prefix. Everyone who opens the workbook needs the add-in too, otherwise they see #NAME?. A UDF also requires macros to be enabled; in a workbook with macros disabled every UDF cell shows #NAME? or keeps its last value until recalculation.

Watch out. UDFs do not work in Excel for the web and they are much slower than built-in functions. Before writing one, check whether LET, LAMBDA or a built-in function already does the job. A named LAMBDA is a formula-only alternative that works everywhere, including the web.

Common mistakes

  • Putting the UDF in a sheet module: cells show #NAME?.
  • Naming it like a cell address (VAT2026), or the same as its module.
  • Reading cells inside the function that are not arguments: results go stale.
  • Making every UDF volatile "just to be sure": the workbook becomes sluggish.
  • Expecting the function to format or write to other cells: it cannot.
  • Declaring a typed parameter such as As Double and passing text: the cell shows #VALUE!. Use Variant parameters when you want to handle bad input yourself.

Check yourself

1. Where must a UDF be placed so it can be used in a worksheet cell?

2. A UDF reads a tax rate from Settings!B1 internally (not as an argument). What happens when B1 changes?

3. How does a UDF return #VALUE! to the cell on purpose?

4. Your UDF contains Range("E1").Value = 0. What happens when it is used in a cell?

5. What is the best way to make your UDFs available in every workbook on your computer?

⬇Practice workbookExamples with live formulas + practice sheets · .xlsx · 14 KB