Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel User Defined Function: How to Create One

· 8 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

A user defined function (UDF) in Excel is a custom formula you write yourself, usually in VBA, that behaves like a built-in function such as =SUM() or =VLOOKUP(). You type =MyFunction(A1) in a cell and Excel returns a result, complete with the same autocomplete, argument helper and error handling as native functions. You can create one by opening the Visual Basic Editor (Alt+F11), inserting a standard module, writing a Function block that returns a value, then saving the workbook as an .xlsm file. This is the route to use when a formula would become an unreadable nest of IFs, or when you repeat the same calculation across dozens of sheets.

This guide covers the Windows desktop version of Excel, where the Visual Basic Editor is built in. On Excel for Mac the editor exists but behaves slightly differently in places, and on Excel for the web you cannot write VBA at all — you can only use functions already stored in a macro-enabled workbook opened there, and even that is limited. Menu labels and dialog wording can differ a little by Excel version and region.

What You'll Need

  • Excel for Windows (Microsoft 365 or a recent perpetual version such as 2019 or 2021). Some Microsoft 365 builds no longer install the VBA editor by default, so check File > Options > Customize Ribbon for a Developer tab first.
  • The Developer tab visible on the ribbon. If it is missing, right-click any tab, choose Customize the Ribbon, tick Developer in the right-hand list, and click OK.
  • A workbook saved as .xlsm (Excel Macro-Enabled Workbook) if you want the function to persist. A plain .xlsx file discards VBA on save.
  • Macro security set to allow your own code to run. Macros are typically blocked from running in files downloaded from the internet until you enable them or unblock the file in its properties.

Step-by-Step

  1. Create or open a macro-enabled workbook. Start from a blank workbook, then use File > Save As and pick Excel Macro-Enabled Workbook (*.xlsm). Do this before writing code, so a stray save does not wipe your work. Give it a clear name like CustomFunctions.xlsm.
  2. Open the Visual Basic Editor. Press Alt+F11, or click Developer > Visual Basic. A separate grey window opens. If you see nothing familiar, check the left-hand Project Explorer: your workbook should be listed as a VBAProject node.
  3. Insert a standard module. In the editor, choose Insert > Module. A blank code pane appears on the right. Insert the module inside your own workbook's project, not inside a sheet object or ThisWorkbook — those are for event code, not for public functions. Give the module a descriptive name in the Properties window (F4), for example modTextTools.
  4. Write the function. Type a block starting with Public Function, the function name, its arguments in brackets, and a return type, then end with End Function. For a working example that strips spaces and returns a clean text value:

    Public Function CleanText(ByVal txt As String) As String
    CleanText = Trim(Application.WorksheetFunction.Clean(txt))
    End Function

  5. Name it so Excel will accept it. The name must start with a letter, contain no spaces, and must not clash with a cell reference (so Tax1 is risky because it looks like a cell address). It also must not duplicate a built-in function name. Use a short prefix such as fn or your initials to avoid collisions.
  6. Compile and test. In the editor, use Debug > Compile VBAProject. Any syntax error is flagged and the offending line highlights. Fix it, compile again until it passes.
  7. Return to the worksheet and call it. Press Alt+F11 to switch back. Click a cell and type =CleanText(A1). As you type the opening bracket, Excel should show the argument name in a tooltip. Press Enter and the result appears.
  8. Use it across a range. Fill the formula down or across as normal — =CleanText(B2), =CleanText(B3) and so on. Relative references behave exactly as they do with built-in functions.
  9. Save as .xlsm again. Press Ctrl+S. If Excel warns that the file contains macros, accept the prompt — you chose the macro-enabled format, so this is expected.
  10. Make the function reusable. To use it in other workbooks, either open both files and reference it as =CustomFunctions.xlsm!CleanText(A1) while both are open, or copy the module into the second workbook (right-click the module name in Project Explorer and choose Export File, then Import File in the target). Store it in your Personal Macro Workbook only if you are comfortable with it loading invisibly every time Excel starts.

Common Mistakes

Writing the function in a sheet module. Code placed in a Worksheet or ThisWorkbook object is private by default and will not appear in the formula list. Public functions belong in a standard module.

Saving as .xlsx. This is the single most common cause of vanished code. Excel strips VBA when you save to a non-macro format, usually with a warning you may dismiss without reading.

Declaring a variable type the function cannot return. Declaring As Integer when the result might exceed its range causes an overflow error. Use As Long for whole numbers over about 32,000, and As Variant when the result could be text or an error.

Expecting the function to recalculate when its inputs change indirectly. A UDF only recalculates when its arguments change or when Excel forces a full calculation (Ctrl+Alt+F9). If your function reads a cell that is not passed as an argument, the result can go stale. Pass every input as an argument instead of hard-coding cell references or reading other cells from inside the function.

Forgetting error handling. An unhandled runtime error returns #VALUE! with no clue why. Add a simple check at the top of the function and return a clear value or use CVErr(xlErrValue) deliberately.

Using volatile behaviour everywhere. Calling Application.Volatile makes the function recalculate on every change, slowing large sheets. Add it only if the function genuinely depends on something outside its arguments, such as the current time.

Tips

Start with the return type. Deciding As String, As Double or As Variant before writing the body prevents most type errors and makes the argument tooltip clearer.

Add a short description in the Macro dialog (Developer > Macros) or as a comment block above the function so colleagues know what it does and what each argument expects. Excel will not show it in the formula tooltip, but it saves confusion later.

If you need to deploy a function to a whole team, consider distributing the workbook as an Excel add-in (.xlam) instead of a shared .xlsm. Users install it through File > Options > Add-ins, and the functions appear in every workbook without opening a source file.

For modern Excel, check whether a native function now does the job — text cleanup, lookups and splitting have been improved substantially over the years, and a built-in formula is easier to audit than VBA.

Troubleshooting

The function does not appear in autocomplete. Confirm the module is a standard module in the right project, the function is declared Public (or at least not Private), and the code compiled without errors. Also check that macros are enabled — if the security bar shows macros disabled, the function is invisible.

You get #NAME?. Excel cannot find the function. Usually the name is misspelled, the module was never saved, or the workbook is open in a version without VBA — Excel for the web cannot run or even resolve your custom functions.

You get #VALUE!. An argument of the wrong type reached the function. Check whether the cell you passed contains text where a number is expected, or a blank where the function assumes a value. Wrap the call in IFERROR for a cleaner display.

The result will not update. Force a recalculation with Ctrl+Alt+F9. If that fixes it, your function reads data outside its arguments — rewrite it to take that data as a parameter.

The macro warning keeps appearing. Confirm the file is .xlsm, then check File > Options > Trust Center > Trust Center Settings > Macro Settings. Do not lower security globally to make a warning go away; instead add a trusted location for your own project folder.

If none of that works, export the module, delete it, re-import it, and test with a one-line function such as Public Function TestIt() As String
TestIt = "ok"
End Function
. If that resolves, the problem is in your original code, not Excel.

Frequently Asked Questions

Can I create a UDF without VBA?

Not as a true custom function. Modern Excel has LAMBDA and named functions, which let you save a formula under a name without VBA, but they require Microsoft 365 and they are still spreadsheet formulas, not code. Older versions and Excel for the web have no way to add a genuinely new function without VBA.

Do user defined functions work on Mac and in Excel for the web?

VBA exists in Excel for Mac, though the editor differs and some Windows-only features will not run. Excel for the web cannot run VBA; it can open a macro-enabled workbook, but custom functions generally return errors there. Use the desktop app for anything involving UDFs.

Why did my function disappear after I reopened the file?

The workbook was almost certainly saved as .xlsx rather than .xlsm, which removes all VBA. Re-create the module and save with the macro-enabled format immediately.

Can a UDF change a cell's formatting or another cell's value?

No. A function called from a worksheet cell can only return a value. Changing cells or formatting is a macro action, not a function action, and attempting it from a UDF fails or behaves unpredictably.

Will my UDF work if someone opens the file without macros enabled?

No. The function name resolves to an error such as #NAME? until macros are enabled. Tell recipients to enable macros for that file, or supply an add-in with clear instructions.