You have a worksheet full of values that need the same small calculation: turn a product code into a category, add a surcharge based on a rule, or format a name consistently. The formula is not difficult once. It becomes tedious when you repeat it across hundreds of rows.
Excel includes a large library of built-in functions, but no built-in function can know every rule used by your team. That is where VBA can help. A custom worksheet function lets you write a rule once and then use it in cells much like SUM, IF, or VLOOKUP.
These functions are often called User-Defined Functions, or UDFs. They can make a workbook clearer, reduce duplicated formulas, and give business rules a meaningful name.
The key is to use them for the right jobs. A well-designed UDF is small, predictable, and easy for someone else to understand.
🧩 What a custom worksheet function is
A UDF is a VBA Function procedure that returns a value. After you place it in the right kind of VBA module, Excel can call it from a worksheet formula.
For example, a function named NetPrice might allow a cell formula such as =NetPrice(A2,B2). Excel passes the two cell values into VBA, runs your calculation, and displays the returned result.
🔍 Why built-in formulas are not always enough
Built-in formulas should usually be your first choice. They are familiar, fast, and work in workbooks where macros are disabled.
A UDF becomes useful when a calculation contains a stable organization-specific rule, would otherwise require a long repeated formula, or needs logic that would be hard to read in a cell. Naming that rule can also make a sheet more self-explanatory.
🛠️ What you need before you begin
You need a desktop version of Excel that supports VBA and permission to use macros in the workbook. Excel for the web can display many workbook results, but it does not run or edit VBA code.
Save the file as an Excel Macro-Enabled Workbook with the .xlsm extension. A normal .xlsx file cannot retain VBA code when saved.
⌨️ Opening the Visual Basic Editor
Press Alt+F11 to open the Visual Basic Editor, often abbreviated as VBE. If you prefer the ribbon, enable the Developer tab in Excel options and choose Visual Basic.
The Project Explorer normally appears on the left. It lists open workbooks and their components, including worksheets, workbook objects, modules, and user forms.
📦 Putting the code in a standard module
In the VBE, select your workbook, then choose Insert > Module. Excel creates a standard module, usually named something like Module1.
Put worksheet UDFs here rather than in a worksheet code module or the ThisWorkbook object. A standard module makes the function available to the workbook’s worksheets in the expected way.
🏗️ Understanding the smallest possible function
Every VBA function has a name, optional input arguments, and a value assigned back to that name. Here is a simple example:
Public Function DoubleValue(ByVal Number As Double) As Double
DoubleValue = Number * 2
End Function
In a cell, enter =DoubleValue(A2). If A2 contains 12, Excel displays 24. The line DoubleValue = is not merely a comparison; it assigns the result the function will return.
🧠 Reading the function declaration
Public makes the function available outside its module, including on worksheets. Function declares the procedure type, and As Double states that its result is a decimal number.
ByVal passes a copy of an input value. It prevents the procedure from changing the caller’s variable, which is a sensible default for calculation functions.
🔢 Choosing useful data types
Types help VBA interpret data correctly and can expose mistakes early. Use Double for most numeric calculations, String for text, Date for dates, and Boolean for True/False values.
Use Variant only when a function genuinely needs to accept or return different kinds of values, including Excel errors. It is flexible, but it offers less protection against accidental mismatches.
🧾 Your first practical example: a tiered discount
Suppose a store applies 5% discount at 100 units and 10% at 500 units. This is a hypothetical business rule, but it demonstrates conditional logic clearly.
Public Function QuantityDiscount(ByVal Units As Double) As Double
If Units >= 500 Then
QuantityDiscount = 0.1
ElseIf Units >= 100 Then
QuantityDiscount = 0.05
Else
QuantityDiscount = 0
End If
End Function
Use =QuantityDiscount(B2) and format the result cell as a percentage. Keeping the function focused on one result makes it reusable.
🧮 Returning a final calculation instead
You may prefer a function that returns the discounted price directly. This can be clearer when users should not see or reuse the discount rate.
Public Function DiscountedTotal(ByVal UnitPrice As Double, ByVal Units As Double) As Double
DiscountedTotal = UnitPrice * Units * (1 - QuantityDiscount(Units))
End Function
This example shows that one UDF can call another. Still, do not build deep chains without need; debugging is easier when each function remains straightforward.
📝 Giving arguments meaningful names
Names such as UnitPrice, Units, and StartDate explain intent better than x, y, and z. Clear names matter because users may only see the worksheet formula, not the code.
Likewise, choose function names that describe the outcome: ShippingCharge, IsValidDepartmentCode, or NormalizePhoneNumber. Avoid vague names such as Calculate.
🧷 Requiring and checking inputs
Do not assume every referenced cell contains a valid value. Blank cells, text in numeric columns, and error values are routine parts of real spreadsheets.
Public Function SafePercent(ByVal Part As Variant, ByVal Total As Variant) As Variant
If Not IsNumeric(Part) Or Not IsNumeric(Total) Then
SafePercent = CVErr(xlErrValue)
ElseIf CDbl(Total) = 0 Then
SafePercent = CVErr(xlErrDiv0)
Else
SafePercent = CDbl(Part) / CDbl(Total)
End If
End Function
CVErr returns an Excel-style error. This is often more honest than quietly returning zero when the input is invalid.
🚦 Handling blank cells deliberately
A blank cell may mean “not entered yet,” “not applicable,” or simply zero. Those meanings are different, so decide which rule your function should follow.
For a function receiving a cell value, IsEmpty can identify an empty Variant. If a blank should produce an empty-looking result, return ""; if it should block calculation, return an appropriate error instead.
⚠️ Showing errors users can understand
Excel error values communicate that a calculation cannot produce a valid result. Common choices include xlErrValue for the wrong kind of input, xlErrNum for an invalid numeric condition, and xlErrNA when no matching answer exists.
Do not use broad error suppression such as On Error Resume Next as a shortcut. It can hide programming errors and return misleading results. Check expected conditions explicitly.
🧭 Using optional arguments for sensible defaults
An optional argument lets a formula stay short while still allowing an override. Consider a shipping function with a default rate:
Public Function ShippingCost(ByVal Weight As Double, _
Optional ByVal RatePerKg As Double = 2.5) As Double
ShippingCost = Weight * RatePerKg
End Function
Users can enter =ShippingCost(C2) or =ShippingCost(C2,3). Defaults should be documented and stable, especially when they represent a policy.
📅 Working carefully with dates
Excel stores dates as serial numbers, while VBA can treat them as Date values. A UDF can accept a date, but regional date formats can make text dates ambiguous.
When possible, pass actual Excel date cells rather than typed date strings. Use explicit functions such as DateSerial when constructing dates in code.
🔤 Cleaning text with a UDF
A text-cleaning function is a good UDF use case when a team repeats the same normalization rule. The following hypothetical example trims outer spaces and converts text to uppercase:
Public Function StandardCode(ByVal RawCode As String) As String
StandardCode = UCase$(Trim$(RawCode))
End Function
Use =StandardCode(A2). Before writing your own text UDF, check whether Excel’s built-in TRIM, UPPER, CLEAN, or newer text functions already solve the problem.
📚 Looking up values without hiding the source
A UDF can perform a lookup, but built-in tools such as XLOOKUP, INDEX/MATCH, and tables are often more transparent for ordinary lookup tasks.
Use a custom function when the lookup has specialized matching, validation, or fallback rules. Make its inputs explicit, and document where it obtains data so users can trace results.
🧱 Keeping functions free of side effects
A worksheet UDF should calculate and return a value. It should not write into other cells, delete content, display message boxes, change formatting, or alter workbook structure.
This restriction is practical as well as conceptual. Excel may recalculate a formula at times you do not expect. A function that changes the workbook during calculation creates confusing and unreliable behavior.
🔄 Understanding recalculation
Excel recalculates formulas when precedent cells change and under other calculation conditions. A UDF recalculates when Excel recognizes that one of its referenced arguments has changed.
If a function depends on something not passed as an argument, Excel may not know when to update it. Pass relevant cells or values into the function rather than relying on hidden dependencies.
⚡ Why volatile functions need restraint
Application.Volatile tells Excel to recalculate a UDF whenever calculation occurs. That may be appropriate for a function based on the current time, but it can slow larger workbooks.
Use volatility only when the result truly depends on changing information that Excel cannot track through arguments. Most business-rule UDFs should not be volatile.
🏎️ Avoiding slow cell-by-cell code
A UDF that reads many worksheet cells one at a time can become slow when copied through thousands of rows. Each interaction between VBA and the worksheet has overhead.
Where possible, pass the needed range as an argument and read it into a VBA array once. Also avoid unnecessary loops, repeated worksheet-function calls, and calculations that can be performed by a built-in formula.
📊 Accepting a range as an argument
A range argument allows a UDF to evaluate a group of cells. For example, this function counts numeric entries above a threshold:
Public Function CountAbove(ByVal Values As Range, ByVal Limit As Double) As Long
Dim Cell As Range
For Each Cell In Values.Cells
If IsNumeric(Cell.Value) Then
If Cell.Value > Limit Then CountAbove = CountAbove + 1
End If
Next Cell
End Function
Call it with =CountAbove(B2:B20,100). For this exact task, Excel’s COUNTIF is better; the example illustrates the range pattern, not a reason to replace built-ins.
🧪 Testing before filling a whole column
Test a UDF with normal values, zero, blanks, text, negative values when relevant, and boundary values such as exactly 100 or 500. Boundary tests reveal whether > and >= reflect the intended rule.
Build a small test area in the workbook with expected outputs. This gives you a quick regression check after changing the code.
🐞 Debugging with the VBE
Click in a procedure and press F8 to step through code line by line. Use the Immediate window, opened with Ctrl+G, to inspect simple expressions or print temporary values with Debug.Print.
A breakpoint, created by clicking the margin beside a line, pauses execution at a chosen point. These tools are safer than guessing why a worksheet result is wrong.
🪪 Making functions discoverable in Excel
Functions stored in a standard module can appear in Excel’s Insert Function dialog under the User Defined category. Give them clear names because that may be the only clue a colleague sees.
You can add a description with Application.MacroOptions, usually from a setup macro. This is optional, but valuable in workbooks intended for repeated use by others.
📖 Documenting the business rule
Code comments explain implementation; worksheet notes or a documentation sheet explain the user-facing rule. Record what each argument means, units expected, blank-cell behavior, error behavior, and examples.
Also identify the function version if rules may change. A formula can remain syntactically valid while its underlying policy becomes outdated.
🔐 Macro security and sharing
Recipients may open a macro-enabled workbook with macros disabled. In that state, UDF formulas may not calculate as intended because the VBA code cannot run.
Share macro-enabled files only through trusted channels, explain why macros are present, and never ask users to enable macros from an unknown source. Organizations may apply their own macro-security policies.
🧰 Choosing between a workbook function and an add-in
A UDF inside one .xlsm workbook travels with that workbook. This is convenient for a self-contained model, but each copy can develop separately.
An Excel add-in is more suitable when a stable library of functions is used across many workbooks. It requires more deployment planning, version control, and support, but centralizes maintenance.
🧹 Avoiding common design mistakes
- Recreating a built-in formula when the built-in version is clearer and faster.
- Mixing calculation, formatting, and data changes in the same UDF.
- Depending on active sheets, selected cells, or hidden workbook state.
- Returning zero for every error, which can make bad data look valid.
- Using unclear names or undocumented units.
A reliable UDF behaves like a small calculator: the same valid inputs produce the same result, without surprising changes elsewhere.
🧩 A complete reusable example
Here is a compact function that calculates a late fee from an invoice amount and days overdue. The rules are hypothetical: no fee through seven days, then 1% plus 0.1% per additional day.
Public Function LateFee(ByVal InvoiceAmount As Variant, _
ByVal DaysOverdue As Variant) As Variant
If Not IsNumeric(InvoiceAmount) Or Not IsNumeric(DaysOverdue) Then
LateFee = CVErr(xlErrValue)
ElseIf CDbl(InvoiceAmount) < 0 Or CDbl(DaysOverdue) < 0 Then
LateFee = CVErr(xlErrNum)
ElseIf CDbl(DaysOverdue) <= 7 Then
LateFee = 0
Else
LateFee = CDbl(InvoiceAmount) * (0.01 + (CDbl(DaysOverdue) - 7) * 0.001)
End If
End Function
Enter =LateFee(B2,C2). Notice the sequence: validate inputs, reject impossible values, handle the simple case, then calculate the remaining case.
✅ The core principle: make rules readable and dependable
A custom Excel function is most valuable when it turns a repeated, well-defined rule into a short formula that people can understand and trust. It is not a replacement for every built-in function or a way to hide complicated logic.
Start with one focused function, place it in a standard module, validate inputs, return meaningful results or errors, and test realistic edge cases. Keep dependencies explicit and avoid actions that alter the workbook during calculation.
The best VBA UDFs act like well-labeled tools: small enough to verify, clear enough to reuse, and dependable enough to support real decisions.
Once you adopt that approach, a worksheet formula can carry not only a calculation, but a clear piece of your organization’s working knowledge. ⚙️📊✨

