Who this lesson is for, and the problem it solves
You already record macros, or you have written a Sub or two that formats a report or copies rows from one sheet to another. Now you keep hitting the same wall in ordinary formulas: a calculation that needs four nested functions, that nobody in the team can read, and that you copy from an old file every month because you would never get it right from memory. Pulling an order number out of an e-mail subject is the classic case. The built-in answer works, but it is a line of MID and SEARCH that breaks the moment someone edits it.
A user-defined function, or UDF, is the way out. You write the logic once in VBA, give it a name, and from then on the sheet uses it like SUM or VLOOKUP: =TextBetween(A2,"[","]"). This free first lesson explains the one idea everything else in the course rests on, the difference between a Sub and a Function, and walks through the TextBetween function from the lab above line by line. By the end you will know why a working function can still show #NAME? in a cell, and how to fix it in under a minute.
The core idea: a Sub does, a Function answers
VBA has two kinds of procedure. A Sub is a list of instructions. You run it from the macro list (Alt+F8), from a button or with F5 in the editor, and it changes things: it writes values, formats ranges, adds sheets, saves files. When it finishes, nothing comes back to the caller. A Function is also a list of instructions, but it ends by handing exactly one value back to whoever called it. Because it hands a value back, it can sit on the right-hand side of an assignment in VBA, and it can sit inside a formula in a cell.
That single difference explains most of the rules you will meet later. A cell can only ask questions, so it can only call a Function. A Function called from a cell is expected to behave like a formula, so Excel does not let it change other cells, formatting or sheets while the workbook is calculating. A Sub never appears in a formula, so it may change anything it likes. Keep the sentence "a Sub does something, a Function answers something" in mind and the rest of the course falls into place.
There is no Return keyword in VBA
If you come from Python, JavaScript or C#, this is the line that looks wrong. VBA does not have a Return statement for values. Instead, you assign the answer to the name of the function itself. Inside Function Perimeter, the line Perimeter = 2 * (width + height) is not creating a variable called Perimeter. It sets the value that will leave the function when it reaches End Function or Exit Function.
Function Perimeter(width As Double, height As Double) As Double
Perimeter = 2 * (width + height)
End Function
The As Double after the closing bracket is the type of the answer. If the function never assigns to its own name, it returns the empty value of that type: 0 for a Double or Long, an empty string for a String, False for a Boolean. That sounds like a bug waiting to happen, and sometimes it is. In TextBetween it is used on purpose: when no marker is found, the function simply leaves early and the cell shows nothing instead of an error.
The worked example: order numbers from e-mail subjects
The lab gives you four e-mail subjects, as they might arrive from a shared support inbox or an export from your order system. Three contain an order reference in square brackets, one contains none. The DemoTextBetween Sub writes them into column A of a sheet called UDF Demo, calls the function from VBA to fill column B, and writes a real worksheet formula into column C. The table shows the result, next to what the two built-in approaches return on the same data.
| Row | A: Subject | B: called from VBA | C: =TextBetween(A2,"[","]") | MID + SEARCH | TEXTBEFORE(TEXTAFTER()) |
|---|---|---|---|---|---|
| 2 | Order [SO-4471] shipped on Monday | SO-4471 | SO-4471 | SO-4471 | SO-4471 |
| 3 | RE: order [SO-4472] delivery question | SO-4472 | SO-4472 | SO-4472 | SO-4472 |
| 4 | Invoice for [SO-4473] attached | SO-4473 | SO-4473 | SO-4473 | SO-4473 |
| 5 | No reference anywhere in this one | (empty) | (empty) | #VALUE! | #N/A |
The two built-in formulas in the last columns are the ones people normally write. The classic version works in every Excel version:
=MID(A2,SEARCH("[",A2)+1,SEARCH("]",A2,SEARCH("[",A2)+1)-SEARCH("[",A2)-1)
In Microsoft 365 and Excel 2024 the newer text functions make it shorter: =TEXTBEFORE(TEXTAFTER(A2,"["),"]"). Both are correct. Both also fail loudly on row 5, where there is no bracket, so in a real sheet you would wrap them in IFERROR(…,"") and make them longer still. The UDF does the same job, returns an empty string on row 5 by design, and reads like a sentence. For a one-off extraction, the built-ins are the right tool. For a pattern you use every week, in many files, a well-named function pays for itself quickly.
The code from the lab, explained
Here is the function itself. It lives in a standard module, it takes three Strings and returns one String.
Option Explicit
Function TextBetween(ByVal source As String, ByVal opener As String, _
ByVal closer As String) As String
Dim startPos As Long
Dim endPos As Long
startPos = InStr(1, source, opener, vbTextCompare)
If startPos = 0 Then Exit Function
startPos = startPos + Len(opener)
endPos = InStr(startPos, source, closer, vbTextCompare)
If endPos = 0 Then Exit Function
TextBetween = Mid(source, startPos, endPos - startPos)
End Function
Option Explicitforces you to declare every variable withDim. A typo such asstartPsothen stops the code at compile time instead of silently creating a new, empty variable.ByValpasses a copy of each argument. The function cannot accidentally change a variable belonging to the code that called it, which keeps a UDF predictable.InStr(1, source, opener, vbTextCompare)returns the position of the first opener, counting from 1, or0when there is none.vbTextComparemakes the search ignore case, which matters when your markers are letters such as"Ref:".If startPos = 0 Then Exit Functionis the early exit. BecauseTextBetweenwas never assigned, the function returns an empty string.startPos = startPos + Len(opener)moves past the marker. With a one-character marker this adds 1, with"Ref:"it adds 4. Forget this line and the result starts with the bracket.- The second
InStrstarts searching atstartPos, so it finds the closing bracket after the opener, not one that happens to appear earlier in the text. Mid(source, startPos, endPos - startPos)takes exactly the characters between the two markers, and assigning it toTextBetweensends the answer back.
The demo Sub is the other half of the lab. The interesting part is the loop:
For r = 0 To UBound(samples)
ws.Cells(r + 2, 1).Value = samples(r)
ws.Cells(r + 2, 2).Value = TextBetween(CStr(samples(r)), "[", "]")
ws.Cells(r + 2, 3).Formula = "=TextBetween(A" & (r + 2) & ",""["",""]"")"
Next r
Column B receives a plain value: VBA called the function, got SO-4471, and wrote that text into the cell. Column C receives a formula, so the cell calls the function itself and recalculates whenever column A changes. Type a new subject into A3 and C3 updates at once, B3 does not. CStr(samples(r)) is needed because samples is a Variant array and the argument is declared As String, and the doubled quotes inside the formula string are how VBA writes one quote character.
Step by step: build it in your own workbook
- Open a new or existing workbook and press
Alt+F11to open the Visual Basic Editor. On a Mac useOpt+F11or Tools → Macro → Visual Basic Editor. - In the Project Explorer (
Ctrl+Rif it is hidden), select your workbook, then choose Insert → Module. A new item called Module1 appears under a folder named Modules. - Paste the function and the demo Sub from the lab into the empty code window. Make sure
Option Explicitappears only once, at the very top. - Click anywhere inside
DemoTextBetweenand pressF5. The Sub creates the UDF Demo sheet, or reuses it if it already exists, and fills columns A to C. - Switch back to Excel with
Alt+F11. Click C2 and look at the formula bar: it shows=TextBetween(A2,"[","]"), a normal formula. - In an empty cell, start typing
=Text. Your function appears in the formula autocomplete list next toTEXTandTEXTJOIN. PressShift+F3to open Insert Function and pick the category User Defined to see it there too. - Change A2 to
Order [SO-9001] cancelledand press Enter. C2 now shows SO-9001, while B2 still shows the old value written by the Sub. - Save with
F12and choose Excel Macro-Enabled Workbook (*.xlsm). A normal .xlsx silently drops the module, and every formula using the function turns into#NAME?the next time the file is opened.
Ctrl+G and type ? TextBetween("Ref [A-12] ok", "[", "]"), then press Enter. The answer appears on the next line.
Sub and Function side by side
The table sums up what each kind of procedure can and cannot do. It is worth reading twice, because almost every UDF problem in the later lessons comes back to one of these lines.
| Question | Sub | Function |
|---|---|---|
| Returns a value to the caller? | No | Yes, by assigning to its own name |
Listed in Alt+F8? | Yes (if Public and without arguments) | No |
| Usable in a cell formula? | No | Yes, from a standard module |
| May change other cells, formats or sheets? | Yes | Not when called from a cell |
| Can take arguments? | Yes | Yes |
| Callable from other VBA code? | Yes, Call MySub or MySub | Yes, x = MyFunction(...) |
| Runs when the sheet recalculates? | Never | When its inputs change (more in lesson 6) |
The trap: it works in VBA, and the cell says #NAME?
This is the single most common first-week UDF problem. You test the function from a Sub or the Immediate window, it gives the right answer, and the cell still shows #NAME?. Excel is telling you that it does not know any function with that name. There are four usual causes, and you can check them in this order.
- The code is in the wrong module. Only a standard module, created with Insert → Module, is visible to worksheet formulas. Code typed into Sheet1 or ThisWorkbook under Microsoft Excel Objects belongs to that object. VBA can still reach it as
Sheet1.TextBetween(...), a cell cannot. Cut the code and paste it into Module1. - The name looks like a cell address. A function called
TAX1,VAT21orABC123collides with a real cell, because Excel columns run to XFD. The formula=TAX1(A2)then fails. Avoid names that end in digits, and avoid names of built-in functions such asTRIMorTEXT. - Macros are disabled. If the yellow security bar was not accepted, or the file came from the internet and is blocked, Excel loads the workbook without running any VBA and every UDF formula shows
#NAME?. Enable content, or unblock the file in its properties on Windows, and pressCtrl+Alt+F9. - The function is Private, or lives in another workbook.
Private Functionhides it from the sheet, which is useful for helpers but not for the function itself. A function stored in PERSONAL.XLSB has to be called as=PERSONAL.XLSB!TextBetween(A2,"[","]"). Lesson 8 shows how an add-in removes that prefix.
F2 then Enter, or use Ctrl+Alt+F9 to force a full recalculation, so Excel looks the name up again.Other common mistakes, and how to spot them
- Forgetting to assign the result. The function runs, no error appears, and every cell shows 0 or nothing. Search the function for a line that starts with its own name followed by
=. If there is none, that is the bug. - Trying to change other cells from a UDF. A line such as
Range("D1").Value = 5inside a function called from a cell does not work. The attempt fails and the cell normally shows#VALUE!. If you need to change the sheet, you need a Sub, not a Function. - Using MsgBox for errors. A message box inside a UDF pops up once for every cell that recalculates, which can mean hundreds of dialogs. Return an empty string or, as lesson 3 shows, a real Excel error with
CVErr. - Saving as .xlsx. Excel warns you, but the warning is easy to click past. The formulas survive, the code does not, and the next person to open the file sees
#NAME?everywhere. - Untyped arguments. Leaving out
As StringorAs Doublemakes every argument a Variant. It still runs, but the function accepts anything, including a whole range where you expected one value, and the errors appear far away from their cause. - Off-by-one in Mid. If the result starts with the opening marker or is missing its last character, check the
+ Len(opener)step and the lengthendPos - startPos. Test with a marker longer than one character to be sure.
Quick reference: what this lesson used
Keep this table nearby while you write your first functions.
| Item | What it does | Example |
|---|---|---|
Alt+F11 | Switches between Excel and the VBA editor | (Mac: Opt+F11) |
| Insert → Module | Creates a standard module, the only place for worksheet UDFs | Module1 |
F5 / F8 | Runs the Sub under the cursor / steps through it one line at a time | Run DemoTextBetween |
Ctrl+G | Opens the Immediate window for quick tests | ? TextBetween("a[b]c","[","]") |
Shift+F3 | Insert Function dialog, category User Defined | Lists every public UDF |
Ctrl+Alt+F9 | Forces a full recalculation of all open workbooks | After fixing a #NAME? |
InStr(start, text, find, vbTextCompare) | Position of find in text, 0 if missing | InStr(1, "ab[c", "[") → 3 |
Mid(text, start, length) | Part of a string | Mid("SO-4471", 4, 4) → 4471 |
Len(text) | Number of characters | Len("Ref:") → 4 |
Exit Function | Leaves the function at once with its current value | Early return of an empty string |
Private Function | Hides a helper from worksheet formulas | Callable only from VBA in the same module |
Real-world uses for a simple text UDF
- Order and ticket references. A customer-service team exports its inbox to Excel and pulls the reference in brackets out of every subject, then matches it to the order list with
XLOOKUP. - File names from a scanner or a DMS. A finance team receives invoices named like
INV_2026-0417_SupplierAG.pdfand extracts the invoice number with=TextBetween(A2,"_","_"). - Codes inside product descriptions. A buyer gets supplier price lists where the article number sits in parentheses inside a long description, and needs it in its own column for a lookup.
- Log and system exports. An analyst cleaning an export from a booking or ticketing system pulls the value between
"user="and"&"out of every line. - A shared team toolbox. Once you have five or six such helpers, you put them into one add-in and everyone in the department types the same readable formulas instead of copying long nested ones from old files.
What you will build in the rest of this course
This first lesson is free. Lessons 2 to 8 are part of the paid course, a single one-time purchase of $9.90, and each one adds a skill you will use in real workbooks.
Your First Worksheet Function. You write NetFromGross, a function that takes the VAT out of a gross price, use it on a thousand rows, and give it a description and a category with Application.MacroOptions so it appears properly in the Insert Function dialog, just like a built-in.
Arguments, Types and Error Values. You learn when to take a value and when to take a Range, why ByVal matters for UDFs, and how to return a real #DIV/0! or #VALUE! with CVErr instead of a misleading zero.
Optional Arguments and ParamArray. You make arguments optional with sensible defaults, check whether one was supplied with IsMissing, and build a function that, like SUM, takes any number of ranges and values.
Returning More Than One Value. Your function returns a whole block of results that spills across cells in Microsoft 365, and you learn how the shape of the array decides whether it fills down or across.
Volatile Functions and Recalculation. You find out when Excel calls your function and when it does not, why a function without arguments can show stale results, what Application.Volatile costs, and the better fix of passing in what the function depends on.
Why UDFs Can Be Slow, and What They Cannot Do. You make a slow function many times faster by reading a range into an array in one go, and you get a clear list of what Excel forbids a UDF to do during calculation.
Sharing, Debugging and Living With Your UDFs. You debug functions with a test harness and breakpoints, decide between the workbook, PERSONAL.XLSB and an add-in, and learn what happens when you send a file full of UDFs to someone without the code.
Summary
A Function differs from a Sub in one way that matters: it hands a value back. You send that value by assigning to the function's own name, because VBA has no Return. Put the function in a standard module, give it a name that does not look like a cell address, save the file as .xlsm, and a cell can call it like any built-in formula. When a cell shows #NAME? while VBA gets the right answer, check the module first, then the name, then whether macros are enabled.
Now scroll up to the lab, paste TextBetween and DemoTextBetween into a module, run it with F5, and then change the markers: try =TextBetween(A2,"order ","]") or a subject with two pairs of brackets, and predict the answer before you press Enter.
Frequently asked questions
What is the difference between a Sub and a Function in VBA?
A Sub runs a list of instructions and returns nothing. A Function also runs instructions but hands one value back to the caller, which is why only a Function can be used in a worksheet formula.
How do I return a value from a VBA Function?
Assign the value to the name of the function, for example TextBetween = Mid(source, startPos, endPos - startPos). VBA has no Return statement for values.
Why does my VBA function show #NAME? in a cell?
Usually the function is in a sheet module or ThisWorkbook instead of a standard module, its name looks like a cell address such as TAX1, or macros are disabled. Move it to Insert > Module, rename it if needed and press Ctrl+Alt+F9.
Can a user-defined function change other cells?
No. A Function called from a worksheet formula may only return a value. Attempts to change other cells, formats or sheets fail, and the cell usually shows #VALUE!. Use a Sub for that.
Do I need to save as .xlsm to keep a UDF?
Yes. A normal .xlsx workbook cannot store VBA, so the module is removed when you save and the formulas turn into #NAME? errors. Save as .xlsm, or put the functions in an .xlam add-in.
Where can I find my custom functions in Excel?
Start typing the name after an equals sign and it appears in formula autocomplete. You can also press Shift+F3 and choose the User Defined category in the Insert Function dialog.
Keep going: Custom Functions (UDF)
This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time CHF 9.90.
- Your First Worksheet Function
- Arguments, Types and Error Values
- Optional Arguments and ParamArray
- Returning More Than One Value
- Volatile Functions and Recalculation
- Why UDFs Can Be Slow — and What They Cannot Do
- Sharing, Debugging and Living With Your UDFs