VBA course · Lesson 18 of 33

Using Excel worksheet functions in VBA

Call VLOOKUP, MATCH, SUMIFS and COUNTIF from VBA, handle not-found errors with Application vs WorksheetFunction, use Evaluate and write formulas into cells.

Intermediate 15 min read

VBA has its own built-in functions for text, dates and maths, but it has nothing like SUMIFS, VLOOKUP, MATCH or MEDIAN. Rewriting those in VBA would be slow and error-prone, and there is no need: your code can borrow Excel's worksheet functions directly. This lesson shows the two ways to call them, why their error behaviour differs, how to evaluate a whole formula from code, and how to write formulas into cells instead of values.

WorksheetFunction: the basic way

The object Application.WorksheetFunction (usually shortened to WorksheetFunction) gives access to several hundred Excel functions. Type WorksheetFunction. in the editor and IntelliSense lists them. Arguments are the same as in the cell, but you pass Range objects instead of addresses.

The examples in this lesson use a sheet called Sales:

ABCDE
1OrderRepRegionProductAmount
2S-1001AnaNorthLaptop1200
3S-1002BenSouthMonitor340
4S-1003AnaNorthMonitor310
5S-1004ChloeEastLaptop1150
6S-1005BenSouthLaptop1250
7S-1006AnaEastDock180

The Sales sheet used in the examples

VBA
Option Explicit

Sub SalesSummary()
    Dim ws As Worksheet
    Dim total As Double, anaNorth As Double
    Dim laptops As Long
    Dim biggest As Double

    Set ws = ThisWorkbook.Worksheets("Sales")

    total = WorksheetFunction.Sum(ws.Range("E2:E7"))
    laptops = WorksheetFunction.CountIf(ws.Range("D2:D7"), "Laptop")
    anaNorth = WorksheetFunction.SumIfs(ws.Range("E2:E7"), _
                                        ws.Range("B2:B7"), "Ana", _
                                        ws.Range("C2:C7"), "North")
    biggest = WorksheetFunction.Max(ws.Range("E2:E7"))

    Debug.Print "Total sales: "; total          ' 4430
    Debug.Print "Laptop orders: "; laptops      ' 3
    Debug.Print "Ana in North: "; anaNorth      ' 1510
    Debug.Print "Largest order: "; biggest      ' 1250
End Sub
Totals and counts with WorksheetFunction

Criteria are passed as text exactly as you would type them in a cell, so ">1000" works for "greater than 1000", and you can build criteria from variables: ">" & minAmount.

The trap: when the function returns an error

Lookups often fail: a product code is missing, a name is misspelled. In a cell, a failed VLOOKUP shows #N/A. In VBA, WorksheetFunction.VLookup does something harsher: it raises run-time error 1004 ("Unable to get the VLookup property of the WorksheetFunction class") and your macro stops.

There is a second way to call the same functions: directly on the Application object, without .WorksheetFunction. Then a failed lookup does not raise an error. Instead the function returns an error value (the VBA equivalent of #N/A) that you can test with IsError. The result must go into a Variant, because only a Variant can hold an error value.

Call styleWhen the lookup failsIntelliSense?Result variable
WorksheetFunction.VLookup(...)Run-time error 1004, macro stopsYesAny suitable type
Application.VLookup(...)Returns an error value, macro continuesNoMust be Variant
VBA
Option Explicit

Sub LookupPrice()
    Dim prices As Range
    Dim result As Variant
    Dim code As String

    Set prices = ThisWorkbook.Worksheets("Products").Range("A2:C50")   ' code, name, price
    code = "P-404"

    ' Style 1: Application.VLookup returns an error value instead of failing
    result = Application.VLookup(code, prices, 3, False)
    If IsError(result) Then
        MsgBox "Product " & code & " was not found."
    Else
        MsgBox "Price of " & code & ": " & Format(result, "0.00")
    End If
End Sub

Sub LookupPriceWithHandler()
    Dim prices As Range
    Dim price As Double
    Dim code As String

    Set prices = ThisWorkbook.Worksheets("Products").Range("A2:C50")
    code = "P-404"

    ' Style 2: WorksheetFunction plus an error handler
    On Error Resume Next
    price = WorksheetFunction.VLookup(code, prices, 3, False)
    If Err.Number <> 0 Then
        Err.Clear
        On Error GoTo 0
        MsgBox "Product " & code & " was not found."
        Exit Sub
    End If
    On Error GoTo 0
    MsgBox "Price of " & code & ": " & Format(price, "0.00")
End Sub
Two safe ways to look up a price

Both work. Most developers find the first style cleaner for lookups, because "not found" is a normal situation, not an emergency. Error handling and debugging in VBA explains On Error in depth.

Watch out. A frequent bug: Dim result As Double followed by result = Application.VLookup(...). When the lookup fails you get error 13, Type mismatch, because an error value cannot be stored in a Double. Use Variant with the Application. style.

MATCH to find a row number

MATCH returns a position, which you can turn into a row on the sheet. Remember to add the offset of the first data row.

VBA
Option Explicit

Sub MarkOrderShipped()
    Dim ws As Worksheet
    Dim pos As Variant
    Dim orderNo As String

    Set ws = ThisWorkbook.Worksheets("Sales")
    orderNo = "S-1004"

    pos = Application.Match(orderNo, ws.Range("A2:A7"), 0)
    If IsError(pos) Then
        MsgBox orderNo & " not found."
        Exit Sub
    End If

    ' pos 1 is row 2, so the sheet row is pos + 1
    ws.Cells(pos + 1, "F").Value = "Shipped"
    ws.Cells(pos + 1, "G").Value = Date
End Sub
Finding the row of an order and updating it

pos is 4 here, so the macro writes into F5 and G5. In Microsoft 365 you can also use WorksheetFunction.XLookup and XMatch, but code using them fails with a compile error on Excel 2019 and older, so stick to Match and VLookup if your file is shared widely.

Functions you will not find in WorksheetFunction

Functions that VBA already has in its own language are usually missing from WorksheetFunction. Use the VBA version instead:

In a cellIn VBA
LEFT, RIGHT, MID, LENLeft, Right, Mid, Len
UPPER, LOWERUCase, LCase
TODAY, NOWDate, Now
YEAR, MONTH, DAYYear, Month, Day
ABSAbs
IFIf ... Then ... Else, or IIf
RANDRnd

Watch out for functions that exist in both but behave differently. WorksheetFunction.Trim removes extra spaces inside the text too ("Ana Lee" becomes "Ana Lee"), while VBA's Trim only removes spaces at the ends. VBA's Round uses banker's rounding (Round(2.5, 0) is 2), while WorksheetFunction.Round(2.5, 0) gives 3 like the cell function. For money, the worksheet version is usually what accountants expect. More on this in Operators and expressions in VBA.

Evaluate: let Excel calculate a whole formula

Evaluate takes a formula as text, calculates it exactly as a cell would, and returns the result. It is handy for formulas that are awkward to express as a chain of VBA calls, such as array calculations.

VBA
Option Explicit

Sub EvaluateDemo()
    Dim ws As Worksheet
    Dim laptopRevenue As Variant
    Dim avgOrder As Variant

    Set ws = ThisWorkbook.Worksheets("Sales")

    ' An array formula, calculated in the context of the Sales sheet
    laptopRevenue = ws.Evaluate("SUMPRODUCT((D2:D7=""Laptop"")*E2:E7)")
    Debug.Print "Laptop revenue: "; laptopRevenue    ' 3600

    ' Square brackets are a shortcut for Evaluate (active sheet only)
    avgOrder = [AVERAGE(Sales!E2:E7)]
    Debug.Print "Average order: "; Round(avgOrder, 2)   ' 738.33
End Sub
Using Evaluate and the square-bracket shorthand

Points to note:

  • Double the quotes inside the formula text: ""Laptop"" becomes "Laptop" in the formula.
  • ws.Evaluate evaluates addresses on that sheet. Plain Evaluate or Application.Evaluate uses the active sheet, which may not be the one you mean.
  • The bracket form [A1] or [SUM(B2:B10)] is short, but it cannot contain variables, it is slower and it is hard to search for. Use it in the Immediate window, not in production code.
  • The formula text is limited to 255 characters.
  • If the formula fails, Evaluate returns an error value, so store the result in a Variant and test with IsError.

Writing formulas into cells

Sometimes the right result of a macro is not a value but a formula that keeps working after the macro has finished. Assign the formula text to the Formula property:

VBA
Option Explicit

Sub AddFormulas()
    Dim ws As Worksheet
    Dim lastRow As Long

    Set ws = ThisWorkbook.Worksheets("Sales")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Same relative formula in every row: VAT on the amount
    ws.Range("F1").Value = "VAT"
    ws.Range("F2:F" & lastRow).Formula = "=ROUND(E2*0.24,2)"

    ' A total below the data
    ws.Cells(lastRow + 1, "E").Formula = "=SUM(E2:E" & lastRow & ")"

    ' R1C1 style: "the cell 1 column to the left in the same row"
    ws.Range("G1").Value = "Gross"
    ws.Range("G2:G" & lastRow).FormulaR1C1 = "=RC[-2]+RC[-1]"

    ' Dynamic array formula that should spill (Microsoft 365)
    ws.Range("I1").Formula2 = "=UNIQUE(B2:B" & lastRow & ")"
End Sub
Writing live formulas instead of values

When you write one formula to a multi-row range, Excel adjusts the relative references for each row, exactly like filling down: F3 gets =ROUND(E3*0.24,2) and so on.

There are three formula properties worth knowing:

  • Formula uses A1 references and English function names with commas, regardless of the user's language. Range.FormulaLocal uses the local names and separators, but code written with it breaks in other languages, so avoid it.
  • FormulaR1C1 uses row/column offsets. RC[-2] means "same row, two columns left". Because the text is identical in every row, R1C1 is convenient when you build formulas in loops.
  • Formula2 (Microsoft 365) writes the formula with dynamic-array behaviour, so UNIQUE, FILTER and SORT spill. If you use plain Formula for such a formula, Excel adds the implicit intersection operator @ and you get only one value.
Tip. To see the exact text Excel expects, type the formula in a cell, then in the Immediate window (Ctrl+G) type ?ActiveCell.Formula or ?ActiveCell.FormulaR1C1 and press Enter. Copy the result into your code and double the quotes.

Values or formulas?

If the numbers should update when the data changes, write formulas. If you are producing a final report or exporting data, write values: they are faster and cannot break. A common pattern is to write formulas, let Excel calculate, then freeze them with rng.Value = rng.Value.

Note. Everything in this lesson works the same on Excel for Mac. The only difference is that newer functions such as XLOOKUP and Formula2 require a current Microsoft 365 version on both platforms.

Common mistakes

  • Using WorksheetFunction.VLookup without an error handler and being surprised by error 1004 on a missing code.
  • Storing the result of Application.Match in a Long: a failed match gives Type mismatch.
  • Passing an address as text, WorksheetFunction.Sum("B2:B10"), instead of a range: WorksheetFunction.Sum(Range("B2:B10")).
  • Forgetting to double quotes inside formula strings.
  • Writing a spilling formula with .Formula and getting @ in front of it.
  • Using local function names or semicolons in .Formula: always use English names and commas there.

Check yourself

1. What happens when WorksheetFunction.VLookup does not find the value?

2. You write result = Application.Match(code, rng, 0). Which declaration of result is safe?

3. Which is the VBA way to get today's date, because WorksheetFunction has no TODAY?

4. Which property should you use to write =UNIQUE(B2:B50) so that it spills in Microsoft 365?

5. In a formula string in VBA, how do you write the criterion "Laptop" in quotes?