Tabellab

Function vs Sub: What Actually Differs

Lesson 1 of 8Reading

One does something, the other answers something

You already know the Sub: a block of instructions you run from the macro list or a button. A Function differs in one important way — it hands a value back to whoever called it. A Sub does something; a Function answers something, and because it answers, a cell can ask it.

There is no Return keyword

A Function closes with End Function and declares the type of its answer after the closing bracket. You send that answer back by assigning to the function's own name: the line below is not creating a variable called Perimeter, it is setting the result. Assign nothing and you get an empty value — zero for a number, an empty string for a String.

Function Perimeter(width As Double, height As Double) As Double
    Perimeter = 2 * (width + height)
End Function

Side by side

  • A Sub appears in the Alt+F8 list; a Function never does.
  • A Function can be typed into a cell as =Perimeter(A1, B1); a Sub cannot.
  • A Sub may change cells, formatting and files; a Function called from a cell may not.
  • Both take arguments and can be called from other VBA code.

A function you can use in a cell today

TextBetween pulls whatever sits between two markers out of a string — an order number out of an e-mail subject, a code out of a file name. Paste the whole block into a standard module (Alt+F11, Insert → Module) and run DemoTextBetween with F5.

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

Sub DemoTextBetween()
    Dim ws As Worksheet
    Dim samples As Variant
    Dim r As Long

    samples = Array("Order [SO-4471] shipped on Monday", _
                    "RE: order [SO-4472] delivery question", _
                    "Invoice for [SO-4473] attached", _
                    "No reference anywhere in this one")

    On Error Resume Next
    Set ws = ThisWorkbook.Worksheets("UDF Demo")
    On Error GoTo 0

    If ws Is Nothing Then
        Set ws = ThisWorkbook.Worksheets.Add( _
            After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
        ws.Name = "UDF Demo"
    End If

    ws.Cells.Clear
    ws.Range("A1:C1").Value = Array("Subject", "Called from VBA", "Called from a cell")
    ws.Range("A1:C1").Font.Bold = True

    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

    ws.Columns("A:C").AutoFit
    ws.Activate
End Sub

Line by line

  • Function TextBetween(...) As String — three arguments in, one String out. ByVal means the function works on copies, so it cannot alter the caller's variables.
  • InStr(1, source, opener, vbTextCompare) finds the opening marker and returns 0 when it is not there. vbTextCompare makes the search ignore upper and lower case.
  • If startPos = 0 Then Exit Function — no marker, no answer. The name was never assigned, so an empty string comes out: the missing-Return rule doing something useful instead of crashing.
  • startPos = startPos + Len(opener) steps past the marker itself. Leave it out and the marker turns up in your result.
  • The second InStr starts at startPos, so a closing bracket appearing earlier is correctly ignored.
  • TextBetween = Mid(source, startPos, endPos - startPos) — assigning to the function's own name is how the value leaves.
  • In the Sub, column B calls the function from VBA and column C writes a formula calling the same function from the sheet. One piece of code, two worlds.
  • In "=TextBetween(A" & (r + 2) & ",""["",""]"")" the doubled quotes are how one quote character gets into a VBA string.
  • The last sample has no markers, so both columns stay empty — the Exit Function branch, visible on the sheet.

The trap: it works in VBA and the cell says #NAME?

Two causes, and each of them costs an afternoon the first time.

  • Wrong module. A worksheet function has to live in a standard module — Insert → Module. Typed into a sheet's own module or into ThisWorkbook it stays private to that object: VBA still reaches it as Sheet1.TextBetween(...), a cell answers #NAME?. In the Project Explorer your code must sit under Modules, not under Microsoft Excel Objects.
  • A name Excel reads as an address. Call your function TAX1 and =TAX1(A2) fails, because TAX1 is a legal cell reference — columns run to XFD. A name colliding with a built-in function is just as bad. Avoid a trailing digit, and try a new UDF in a cell before building on it.
A Function called from a cell is what everyone means by a UDF — User Defined Function. It is not a keyword, just an ordinary Function the sheet happens to call. To hide one from the worksheet, write Private Function Helper() As Double.

How this course goes on

Lesson 2 gives your function a description and a category so it appears properly in Excel's function list. Lesson 3 covers argument types and returning a real error such as #DIV/0! instead of a misleading zero; lessons 4 and 5 add optional arguments and functions returning a whole block of cells. The last three save your afternoon: when Excel recalculates a UDF, why a slow one freezes a workbook, and what a UDF is not permitted to do.

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.

One Function, two callersWorksheet cell C2=TextBetween(A2,"[","]")VBA: DemoTextBetweenTextBetween(CStr(...), ...)Function TextBetweenstandard module (Module1)TextBetween = Mid(...)C2 shows SO-4471formula stays in the cellB2 receives SO-4471written as a plain valuecallscallsreturnsreturns
The same Function in a standard module answers two callers: the formula in C2 and the Sub that fills column B. Only the cell keeps a live formula.

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.

RowA: SubjectB: called from VBAC: =TextBetween(A2,"[","]")MID + SEARCHTEXTBEFORE(TEXTAFTER())
2Order [SO-4471] shipped on MondaySO-4471SO-4471SO-4471SO-4471
3RE: order [SO-4472] delivery questionSO-4472SO-4472SO-4472SO-4472
4Invoice for [SO-4473] attachedSO-4473SO-4473SO-4473SO-4473
5No 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.

Characters you type for the same resultFormula length in characters02040608074MID + SEARCH34TEXTBEFORE/AFTER24TextBetween UDF
Length of each formula for the same extraction: 74 characters for MID and SEARCH, 34 for TEXTBEFORE and TEXTAFTER, 24 for the UDF, before any IFERROR wrapper.

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 Explicit forces you to declare every variable with Dim. A typo such as startPso then stops the code at compile time instead of silently creating a new, empty variable.
  • ByVal passes 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, or 0 when there is none. vbTextCompare makes the search ignore case, which matters when your markers are letters such as "Ref:".
  • If startPos = 0 Then Exit Function is the early exit. Because TextBetween was 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 InStr starts searching at startPos, 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 to TextBetween sends 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

  1. Open a new or existing workbook and press Alt+F11 to open the Visual Basic Editor. On a Mac use Opt+F11 or Tools → Macro → Visual Basic Editor.
  2. In the Project Explorer (Ctrl+R if it is hidden), select your workbook, then choose Insert → Module. A new item called Module1 appears under a folder named Modules.
  3. Paste the function and the demo Sub from the lab into the empty code window. Make sure Option Explicit appears only once, at the very top.
  4. Click anywhere inside DemoTextBetween and press F5. The Sub creates the UDF Demo sheet, or reuses it if it already exists, and fills columns A to C.
  5. Switch back to Excel with Alt+F11. Click C2 and look at the formula bar: it shows =TextBetween(A2,"[","]"), a normal formula.
  6. In an empty cell, start typing =Text. Your function appears in the formula autocomplete list next to TEXT and TEXTJOIN. Press Shift+F3 to open Insert Function and pick the category User Defined to see it there too.
  7. Change A2 to Order [SO-9001] cancelled and press Enter. C2 now shows SO-9001, while B2 still shows the old value written by the Sub.
  8. Save with F12 and 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.
To test a function without touching the sheet, open the Immediate window with Ctrl+G and type ? TextBetween("Ref [A-12] ok", "[", "]"), then press Enter. The answer appears on the next line.

Excel VBA custom functions course: a user-defined function used in worksheet cells like a built-in formula
A user-defined function is called from a cell exactly like SUM or VLOOKUP.

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.

QuestionSubFunction
Returns a value to the caller?NoYes, by assigning to its own name
Listed in Alt+F8?Yes (if Public and without arguments)No
Usable in a cell formula?NoYes, from a standard module
May change other cells, formats or sheets?YesNot when called from a cell
Can take arguments?YesYes
Callable from other VBA code?Yes, Call MySub or MySubYes, x = MyFunction(...)
Runs when the sheet recalculates?NeverWhen 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, VAT21 or ABC123 collides 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 as TRIM or TEXT.
  • 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 press Ctrl+Alt+F9.
  • The function is Private, or lives in another workbook. Private Function hides 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.
If you rename or move the function, existing formulas do not update by themselves. Select the cells and press 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 = 5 inside 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 String or As Double makes 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 length endPos - 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.

ItemWhat it doesExample
Alt+F11Switches between Excel and the VBA editor(Mac: Opt+F11)
Insert → ModuleCreates a standard module, the only place for worksheet UDFsModule1
F5 / F8Runs the Sub under the cursor / steps through it one line at a timeRun DemoTextBetween
Ctrl+GOpens the Immediate window for quick tests? TextBetween("a[b]c","[","]")
Shift+F3Insert Function dialog, category User DefinedLists every public UDF
Ctrl+Alt+F9Forces a full recalculation of all open workbooksAfter fixing a #NAME?
InStr(start, text, find, vbTextCompare)Position of find in text, 0 if missingInStr(1, "ab[c", "[") → 3
Mid(text, start, length)Part of a stringMid("SO-4471", 4, 4) → 4471
Len(text)Number of charactersLen("Ref:") → 4
Exit FunctionLeaves the function at once with its current valueEarly return of an empty string
Private FunctionHides a helper from worksheet formulasCallable 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.pdf and 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 €9.90.

  1. Your First Worksheet Function
  2. Arguments, Types and Error Values
  3. Optional Arguments and ParamArray
  4. Returning More Than One Value
  5. Volatile Functions and Recalculation
  6. Why UDFs Can Be Slow — and What They Cannot Do
  7. Sharing, Debugging and Living With Your UDFs

Buy course — €9.90 See the full course

Knowledge check

Your new function returns the right answer when you call it from a Sub, but a cell using it shows #NAME?. What is the most likely cause?

Continues in this course
  • 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

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course — €9.90