Worksheet function in VBA
Categories:
Mastering Excel Worksheet Functions in VBA

Unlock the power of Excel's built-in functions directly within your VBA code to perform complex calculations, data manipulation, and more.
VBA (Visual Basic for Applications) is a powerful tool for automating tasks in Excel. While VBA offers its own set of functions, sometimes the most efficient way to achieve a result is by leveraging Excel's extensive library of worksheet functions. This article will guide you through the process of calling these functions from your VBA code, explaining the syntax, common pitfalls, and best practices.
Why Use Worksheet Functions in VBA?
Excel boasts hundreds of built-in functions, ranging from mathematical and statistical operations to text manipulation, date/time calculations, and lookup utilities. Reimplementing these complex functions in VBA can be time-consuming, error-prone, and often less performant than using the native Excel versions. By calling worksheet functions directly, you can:
- Save Development Time: Avoid writing custom VBA code for operations already handled by Excel.
- Improve Performance: Native Excel functions are highly optimized.
- Ensure Accuracy: Rely on Excel's thoroughly tested and validated functions.
- Enhance Readability: Use familiar function names that are easily understood by other Excel users.
Calling Worksheet Functions: The WorksheetFunction
Object
The primary way to access Excel worksheet functions in VBA is through the Application.WorksheetFunction
object. This object exposes most, but not all, of Excel's worksheet functions as methods. The syntax is straightforward: Application.WorksheetFunction.FunctionName(argument1, argument2, ...)
.
It's crucial to understand that if a worksheet function encounters an error (e.g., #DIV/0!
, #N/A
), the WorksheetFunction
object will raise a VBA run-time error. You must handle these errors using On Error Resume Next
or On Error GoTo
statements if there's a possibility of an error occurring.
Sub UseWorksheetFunction()
Dim rng As Range
Dim sumValue As Double
Dim avgValue As Double
Dim countCells As Long
' Set a range to work with
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A10")
' Calculate the sum of a range
sumValue = Application.WorksheetFunction.Sum(rng)
Debug.Print "Sum: " & sumValue
' Calculate the average of a range
avgValue = Application.WorksheetFunction.Average(rng)
Debug.Print "Average: " & avgValue
' Count non-empty cells
countCells = Application.WorksheetFunction.CountA(rng)
Debug.Print "CountA: " & countCells
' Using a text function
Dim textValue As String
textValue = Application.WorksheetFunction.Proper("hello world")
Debug.Print "Proper Case: " & textValue
End Sub
Example of using common worksheet functions via Application.WorksheetFunction
.
Application.WorksheetFunction
. For functions like SUMIF
, VLOOKUP
, or INDEX
, you might need to use Application.Evaluate
or directly call the function from the Application
object without WorksheetFunction
.Handling Errors with WorksheetFunction
As mentioned, WorksheetFunction
raises a VBA error on Excel function errors. This is different from how Excel itself handles them (displaying error values like #N/A
). To prevent your VBA code from crashing, you must implement error handling. The most common approach is to use On Error Resume Next
and check for errors immediately after the function call.
Sub HandleWorksheetFunctionErrors()
Dim lookupValue As Variant
Dim result As Variant
lookupValue = "NonExistentItem"
' Attempt VLOOKUP, which might result in #N/A
On Error Resume Next ' Enable error handling
result = Application.WorksheetFunction.VLookup(lookupValue, Range("D1:E10"), 2, False)
' Check if an error occurred
If Err.Number <> 0 Then
Debug.Print "Error looking up '" & lookupValue & "': " & Err.Description
' Optionally, set result to a default value or handle the error specifically
result = "Not Found"
Err.Clear ' Clear the error object
Else
Debug.Print "Lookup Result: " & result
End If
On Error GoTo 0 ' Disable error handling
End Sub
Implementing error handling for WorksheetFunction
calls.
Alternative: Direct Call via Application
Object
For some functions, especially those that return error values rather than raising an error, or those not exposed by WorksheetFunction
, you can call them directly from the Application
object. This method often returns the Excel error value (e.g., CVErr(xlErrNA)
) which can then be tested using IsError()
.
Sub DirectApplicationCall()
Dim lookupValue As Variant
Dim result As Variant
lookupValue = "NonExistentItem"
' VLOOKUP directly from Application object
' This will return an error value if not found, not raise a VBA error
result = Application.VLookup(lookupValue, Range("D1:E10"), 2, False)
If IsError(result) Then
Debug.Print "Error looking up '" & lookupValue & "'. Error type: " & result
' You can check specific error types if needed, e.g., If result = CVErr(xlErrNA) Then
Else
Debug.Print "Lookup Result: " & result
End If
End Sub
Using the Application
object directly for functions like VLOOKUP
.
Using Application.Evaluate
for Formula Strings
The Application.Evaluate
method is incredibly versatile. It allows you to evaluate a string as if it were an Excel formula. This is particularly useful for complex formulas, array formulas, or functions not easily accessible otherwise. However, it can be slower than direct calls and might be harder to debug.
Sub UseApplicationEvaluate()
Dim result As Variant
Dim formulaString As String
' Evaluate a simple formula
result = Application.Evaluate("SUM(A1:A10)")
Debug.Print "Sum via Evaluate: " & result
' Evaluate a more complex formula or one not in WorksheetFunction
' Example: SUMIFS (often not directly in WorksheetFunction for older Excel versions)
formulaString = "SUMIFS(B1:B10, A1:A10, ""Category1"")"
result = Application.Evaluate(formulaString)
Debug.Print "SUMIFS via Evaluate: " & result
' Evaluate a formula that returns an error
formulaString = "VLOOKUP(""NonExistent"", D1:E10, 2, FALSE)"
result = Application.Evaluate(formulaString)
If IsError(result) Then
Debug.Print "VLOOKUP via Evaluate resulted in error: " & result
Else
Debug.Print "VLOOKUP via Evaluate: " & result
End If
End Sub
Examples of using Application.Evaluate
to run Excel formulas.
Application.Evaluate
, be mindful of string concatenation for arguments, especially if they contain quotes or references to VBA variables. Ensure the resulting string is a valid Excel formula.Decision Flow for Calling Worksheet Functions
Choosing the right method depends on the specific function and how you want to handle errors. This flowchart illustrates a common decision process.
flowchart TD A[Start] A --> B{Is the function available via Application.WorksheetFunction?} B -- Yes --> C{Does the function typically return an error value (e.g., #N/A) or raise a VBA error?} C -- Raises VBA Error --> D[Use Application.WorksheetFunction with On Error handling] C -- Returns Error Value --> E[Use Application.WorksheetFunction and check IsError() on result] B -- No --> F{Is the function available directly via Application object?} F -- Yes --> G[Use Application.FunctionName() and check IsError() on result] F -- No --> H{Can the function be expressed as an Excel formula string?} H -- Yes --> I[Use Application.Evaluate("Formula String") and check IsError() on result] H -- No --> J[Consider reimplementing in VBA or finding an alternative approach] D --> K[End] E --> K G --> K I --> K J --> K
Decision flow for choosing the best method to call Excel worksheet functions in VBA.
Range
object directly to Application.WorksheetFunction
is generally more efficient than iterating through cells in VBA and performing calculations manually.