Excel VBA Worksheet Function: How to Use It
In this article
You use a worksheet function in VBA by calling it through the WorksheetFunction object, for example Application.WorksheetFunction.Sum(Range("A1:A10")). That gives you Excel's built-in calculation engine inside your macro, so you do not have to rewrite SUM, VLOOKUP, COUNTIF or similar logic by hand. The main catch is that most worksheet functions raise a run-time error instead of returning an error value, so you need error handling around anything that can fail.
What You'll Need
- Excel on Windows or Mac with macros enabled (the Visual Basic Editor is included in every desktop edition).
- A workbook saved as
.xlsmif you want to keep the macro. - Basic familiarity with the Visual Basic Editor: opening it with Alt+F11 on Windows, or Developer > Visual Basic on Mac.
- The Developer tab enabled if you want to insert buttons or run macros from the ribbon. On Windows: File > Options > Customize Ribbon and tick Developer. On Mac: Excel > Preferences > Ribbon & Toolbar.
Menu labels can differ slightly between Excel versions and between Windows and Mac, but the Visual Basic Editor itself works the same way on both.
Step-by-Step
- Open the Visual Basic Editor. Press Alt+F11 on Windows, or choose Developer > Visual Basic on Mac. If you do not see the Developer tab, enable it as described above.
- Insert a module. In the editor, choose Insert > Module. A blank code window opens. Keeping your code in a standard module makes it available to any sheet in the workbook.
- Write a simple function call. Type a short procedure to confirm everything works:
Put some numbers in A1:A10 first, then run the macro with F5.Sub TestSum() Dim total As Double total = Application.WorksheetFunction.Sum(Range("A1:A10")) MsgBox total End Sub - Understand the two ways to call a function.
Application.WorksheetFunction.Sum(...)returns the result and raises an error if the calculation fails.Application.Sum(...)behaves like typing the formula in a cell: it returns an error value instead of stopping the macro. Use the first form when you want to handle problems explicitly, and the second when you want Excel's normal error behaviour. - Pass ranges, not strings, for range arguments. Functions such as SUM, COUNTIF and VLOOKUP expect a Range object. Write
Range("B2:B50"), not the text "B2:B50". Text arguments such as criteria in COUNTIF or SUMIF are passed as normal strings, for exampleWorksheetFunction.CountIf(Range("C2:C50"), "Paid"). - Store the result in a variable of the right type. Use Double for numbers, String for text, Boolean for TRUE/FALSE, and Variant when the function can return more than one type. Assigning a text result to a numeric variable causes a type mismatch.
- Wrap risky calls in error handling. Functions like VLOOKUP, MATCH and FIND raise error 1004 when there is no match. A short handler keeps the macro running:
Sub SafeLookup() Dim result As Variant On Error Resume Next result = Application.WorksheetFunction.VLookup(Range("E2").Value, Range("A2:C100"), 3, False) If Err.Number <> 0 Then result = "Not found" Err.Clear End If On Error GoTo 0 MsgBox result End Sub - Reference the sheet explicitly. Unqualified
Rangecalls act on the active sheet, which changes as the user clicks around. UseWorksheets("Data").Range("A1:A10")or set a worksheet variable once and reuse it, so the macro always reads the sheet you intend. - Use Evaluate for array-style formulas. When a function needs an array argument that VBA cannot pass directly,
Evaluate("SUMPRODUCT((A1:A10=\"Paid\")*(B1:B10))\")runs the formula as if it were typed into a cell. This is slower than a direct call, so keep it for cases where the direct form is awkward. - Test with edge cases. Run the macro on an empty range, a range containing text, and a range containing error values. Worksheet functions propagate errors, so SUM over a range with #N/A returns an error and your call raises 1004.
- Save as a macro-enabled workbook. Use File > Save As and choose Excel Macro-Enabled Workbook (.xlsm). A plain .xlsx file discards the module when closed.
Common Mistakes
- Using a function that is not exposed. Not every worksheet function is available through WorksheetFunction. Some newer dynamic-array functions and a few statistical ones are missing or behave differently. If IntelliSense does not list it, fall back to
Application.EvaluateorApplication.WorksheetFunctionvia late binding. - Forgetting that errors stop the macro. The most common complaint is "it worked in a cell but the macro crashes". That is the error-raising behaviour described above, not a bug.
- Passing a whole column.
Range("A:A")works but is slow. Use a bounded range or find the last row first. - Mixing up 1-based and 0-based arguments. VLOOKUP's column index and MATCH's match type follow Excel's rules, not VBA's. Check the argument order against the formula you already know works in a cell.
- Leaving
On Error Resume Nextswitched on. Always turn it off withOn Error GoTo 0once the risky line has run, or later bugs will be silently swallowed.
Tips
- Use the Object Browser (F2 in the editor) and search for WorksheetFunction to see the full list of available methods for your Excel version.
- For simple arithmetic, plain VBA is faster than a worksheet function call. Use WorksheetFunction when you need Excel's exact behaviour, such as COUNTIF's wildcard matching or TEXT's formatting codes.
- Set a reference to the worksheet once:
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Data"), then callWorksheetFunction.Sum(ws.Range("A1:A10")). - If you need the result to update when data changes, write the formula into the cell instead of calculating it in VBA. A cell formula recalculates automatically; a VBA result does not.
Troubleshooting
Run-time error 1004 "Unable to get the ... property of the WorksheetFunction class". The function could not produce a result: no match, a division by zero, or text where a number was expected. Check the inputs, then add the error handler from step 7.
Run-time error 13 "Type mismatch". You assigned a text result to a numeric variable, or passed a string where a Range was expected. Change the variable to Variant or fix the argument.
The macro returns the wrong sheet's data. Qualify every Range with its worksheet, as in step 8.
"Sub or Function not defined". The function name is misspelled or not available in your Excel version. Check the spelling in the Object Browser and use Evaluate as a fallback.
Nothing happens when you press F5. The cursor may be inside a function rather than a Sub, or macros may be disabled. Check the macro security setting under Developer > Macro Security and confirm the code is in a standard module.
If that did not work, copy the failing line into a cell as a normal formula. If the formula also errors, the problem is the data, not the VBA. If the formula works, re-check the argument types and whether the range is qualified.
Frequently Asked Questions
What is the difference between Application.WorksheetFunction and Application?
WorksheetFunction raises a trappable VBA error when a calculation fails. Calling the function directly on Application returns an Excel error value instead, matching what a cell formula would show.
Can I use any Excel function in VBA?
No. Most common functions are available, but some newer dynamic-array functions and a few specialised ones are not exposed. Use Application.Evaluate for those, or write the formula into a cell.
Why does my VLOOKUP macro crash when there is no match?
Because WorksheetFunction.VLookup raises error 1004 instead of returning #N/A. Wrap it in On Error Resume Next and test Err.Number, as shown in step 7.
Does this work on Excel for Mac?
Yes. The WorksheetFunction object and the Visual Basic Editor are available in Excel for Mac. Menu locations differ slightly, but the code is the same.
Can I call a worksheet function from a cell formula?
No. Worksheet functions are VBA methods. In a cell you use the equivalent built-in function directly, such as SUM or VLOOKUP.
Is WorksheetFunction slower than writing the logic in VBA?
Usually, yes, for simple operations, because each call crosses into Excel's calculation engine. For complex matching or formatting rules it is often faster to develop and less error-prone than hand-written VBA.