Excel VBA: Which Function to Use and When
In this article
Use WorksheetFunction to call Excel's built-in functions from VBA, and write your own Function procedures when you need logic Excel does not provide. The shortest working rule: if the function already exists in Excel (SUM, VLOOKUP, TEXTJOIN, XLOOKUP), call it through Application.WorksheetFunction or Application; if you need custom logic, declare a Function in a standard module. This guide explains how to choose, how to call each type correctly, and the mistakes that cause most VBA function errors.
What You'll Need
- Excel for Windows or Mac with the Developer tab enabled. On Windows: File > Options > Customize Ribbon and tick Developer. On Mac: Excel > Preferences > Ribbon & Toolbar and tick Developer.
- A workbook saved as .xlsm (macro-enabled) if you want to keep your code.
- Basic familiarity with the VBA Editor (Alt+F11 on Windows, Option+F11 on Mac). Menu labels can differ slightly by version, device and region.
Step-by-Step
- Identify whether Excel already has the function. Open a worksheet cell and start typing the function name. If Excel suggests it in the formula autocomplete list, it is a built-in worksheet function and you should call it from VBA rather than rewriting it. Examples: SUM, AVERAGE, COUNTIF, VLOOKUP, XLOOKUP, TEXTJOIN, IFERROR, ROUND, LEFT, MID, DATE.
- Decide between WorksheetFunction and Application. Use
Application.WorksheetFunction.Sum(...)when you want an error to stop your code if the function fails. UseApplication.Sum(...)when you want to handle the error yourself, because this form returns an error value instead of raising a runtime error. For most everyday code, WorksheetFunction is the clearer choice. - Call a built-in function correctly. In the VBA Editor, insert a module (Insert > Module) and write, for example:
Dim total As Doubletotal = Application.WorksheetFunction.Sum(Range("A1:A10"))
Pass ranges or values as arguments exactly as the worksheet function expects. For functions that take criteria, such as COUNTIF, pass the range and the criterion as separate arguments. - Use the WorksheetFunction object to discover arguments. Type
Application.WorksheetFunction.and the editor shows a list of available functions. Type the opening parenthesis and the editor shows the argument list. This is the fastest way to confirm the exact argument order without guessing. - Write a custom Function when no built-in fits. In the same module, add:
Public Function CleanText(ByVal s As String) As StringCleanText = Trim(Replace(s, " ", " "))End Function
A Function returns a value; a Sub does not. Use Function when you need a result back in a cell or in other code. - Call your custom function from a worksheet. Type
=CleanText(A1)in a cell. Custom functions appear in the formula autocomplete list under the module name if the module is a standard module, not a sheet or ThisWorkbook module. - Call your custom function from other VBA code. Use
MsgBox CleanText("hello world")or assign the result to a variable. Keep the function in a standard module so it is visible across the project. - Handle errors deliberately. Wrap calls that might fail in error handling:
On Error Resume Nextresult = Application.WorksheetFunction.VLookup(key, rng, 2, False)If Err.Number <> 0 Then result = "Not found": Err.ClearOn Error GoTo 0
This prevents a missing lookup value from stopping the whole macro. - Test with a small range first. Run the macro on a copy of the workbook, check the output in the Immediate Window (Ctrl+G) using
? Application.WorksheetFunction.Sum(Range("A1:A10")), then scale up.
Common Mistakes
- Using a worksheet function name as if it were native VBA. Writing
x = Sum(Range("A1:A10"))fails because Sum is not a VBA function. Prefix it withApplication.WorksheetFunction.orApplication.. - Putting a custom Function in a sheet module. Functions in Sheet1, ThisWorkbook or a UserForm module are not exposed to worksheet formulas. Move them to a standard module.
- Confusing Function and Sub. A Sub cannot return a value to a cell. If you need a result, declare a Function with a return type.
- Ignoring the difference between WorksheetFunction and Application. WorksheetFunction raises a trappable runtime error on failure; Application returns an error value. Mixing them up leads to either silent wrong results or unexpected crashes.
- Passing the wrong argument type. Built-in functions expect ranges, strings, numbers or arrays in a specific order. Use the editor's argument prompt rather than memory.
- Forgetting to declare variable types. Untyped Variants slow code and hide errors. Declare
As Double,As String,As Rangeand so on.
Tips
- Use
Application.WorksheetFunctionfor readability, and switch toApplicationonly where you need to trap errors without stopping the macro. - Name custom functions clearly and add a short comment describing arguments and return type.
- Keep all reusable functions in one standard module so they are easy to find and call from any procedure.
- Use the Object Browser (F2) to browse the WorksheetFunction members and their signatures.
- Prefer built-in functions over custom code where possible: they are faster, tested, and handle edge cases such as text vs numbers.
- When a custom function will be used in many cells, keep it simple; complex loops in worksheet-called functions can slow recalculation.
Troubleshooting
- "Sub or Function not defined": the function name is misspelled, the module is not a standard module, or the function is in a different project. Check spelling and module type.
- "Unable to get the ... property of the WorksheetFunction class": the built-in function failed, for example VLOOKUP found no match. Add error handling or validate inputs first.
- Custom function returns #NAME?: the module is a sheet module, the function is Private, or macros are disabled. Move it to a standard module and confirm macro security settings allow the workbook.
- Function returns wrong type: the declared return type does not match the value assigned. Change the return type or convert the value.
- Macro runs but cell shows old result: calculation is set to manual. Press F9 or set calculation to automatic in Formulas > Calculation Options.
- Code works on Windows but not Mac: some Windows-only APIs are unavailable. Stick to WorksheetFunction and native VBA for cross-platform code.
Frequently Asked Questions
Should I use WorksheetFunction or Application?
Use WorksheetFunction when you want a failed function to raise an error you can handle with On Error. Use Application when you prefer to check the returned error value instead of trapping a runtime error.
Can I call any Excel function from VBA?
Most worksheet functions are available through WorksheetFunction, but not all. If a function is missing from the list, use Application or replicate the logic in VBA.
Why is my custom function not showing in the formula list?
It is probably in a sheet module, declared Private, or the workbook is not macro-enabled. Move it to a standard module and save as .xlsm.
What is the difference between a Function and a Sub?
A Function returns a value and can be used in worksheet formulas and expressions. A Sub performs actions and does not return a value.
How do I see the result of a function while debugging?
Use the Immediate Window (Ctrl+G) and type a question mark followed by the expression, for example ? CleanText("a b").
Can I use XLOOKUP from VBA?
Yes, if your Excel version supports XLOOKUP on the worksheet, it is available through WorksheetFunction. Older versions do not include it, so check availability before relying on it.