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.
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:
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Order | Rep | Region | Product | Amount |
| 2 | S-1001 | Ana | North | Laptop | 1200 |
| 3 | S-1002 | Ben | South | Monitor | 340 |
| 4 | S-1003 | Ana | North | Monitor | 310 |
| 5 | S-1004 | Chloe | East | Laptop | 1150 |
| 6 | S-1005 | Ben | South | Laptop | 1250 |
| 7 | S-1006 | Ana | East | Dock | 180 |
The Sales sheet used in the examples
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 SubCriteria 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 style | When the lookup fails | IntelliSense? | Result variable |
|---|---|---|---|
WorksheetFunction.VLookup(...) | Run-time error 1004, macro stops | Yes | Any suitable type |
Application.VLookup(...) | Returns an error value, macro continues | No | Must be Variant |
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 SubBoth 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.
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.
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 Subpos 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 cell | In VBA |
|---|---|
| LEFT, RIGHT, MID, LEN | Left, Right, Mid, Len |
| UPPER, LOWER | UCase, LCase |
| TODAY, NOW | Date, Now |
| YEAR, MONTH, DAY | Year, Month, Day |
| ABS | Abs |
| IF | If ... Then ... Else, or IIf |
| RAND | Rnd |
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.
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 SubPoints to note:
- Double the quotes inside the formula text:
""Laptop""becomes"Laptop"in the formula. ws.Evaluateevaluates addresses on that sheet. PlainEvaluateorApplication.Evaluateuses 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,
Evaluatereturns an error value, so store the result in a Variant and test withIsError.
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:
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 SubWhen 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:
Formulauses A1 references and English function names with commas, regardless of the user's language.Range.FormulaLocaluses the local names and separators, but code written with it breaks in other languages, so avoid it.FormulaR1C1uses 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 plainFormulafor such a formula, Excel adds the implicit intersection operator@and you get only one value.
?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.
Common mistakes
- Using
WorksheetFunction.VLookupwithout an error handler and being surprised by error 1004 on a missing code. - Storing the result of
Application.Matchin aLong: 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
.Formulaand 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?
The WorksheetFunction style raises an error; the Application style returns an error value instead.
2. You write result = Application.Match(code, rng, 0). Which declaration of result is safe?
A failed match returns an error value, which only a Variant can hold. Test it with IsError.
3. Which is the VBA way to get today's date, because WorksheetFunction has no TODAY?
VBA has its own Date function, so the worksheet version is not exposed.
4. Which property should you use to write =UNIQUE(B2:B50) so that it spills in Microsoft 365?
Formula2 keeps dynamic-array behaviour; Formula adds the @ operator and returns one value.
5. In a formula string in VBA, how do you write the criterion "Laptop" in quotes?
Inside a VBA string a quote character is written as two quotes.