WorksheetFunction: Excel functions inside VBA
Totals, counting by condition, looking up a price list: Excel already has functions for all of that. WorksheetFunction lets you call them straight from a macro instead of writing your own loops, and you write only the result into the cell.
In short: WorksheetFunction.Sum(Range("B2:B10")) works out the same as =SUM(B2:B10). The functions keep their English names (Sum, Average, CountIf, SumIf, VLookup, Match), and a comma separates the arguments. If WorksheetFunction.VLookup finds nothing, the macro stops; Application.VLookup returns an error value instead, which you test with IsError.
What you need to know: finding the last row and object variables with Set from Variables.
Try it right now
Task Write a macro KeyFigures that uses WorksheetFunction on the sales in column B (row 2 down to the last row) and writes the total to E2, the average to E3 and the highest value to E4.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | Branch | Sales | Measure | Value | |
| 2 | Leeds | 48,200.00 | Total | ||
| 3 | Bristol | 39,750.00 | Average | ||
| 4 | Austin | 27,400.00 | Highest | ||
| 5 | Denver | 31,980.00 | |||
| 6 | Glasgow | 35,600.00 |
How WorksheetFunction works
Dim rng As Range
Set rng = Range("B2:B" & lastRow)
Range("E2").Value = WorksheetFunction.Sum(rng)
Range("E3").Value = WorksheetFunction.Average(rng)
After WorksheetFunction. comes the name of the Excel function, and in parentheses the same arguments as in the formula. Pass ranges as Range objects and criteria as text or numbers. The result is a value, not a formula: if the data changes, the cell does not recalculate on its own.
| Formula | VBA | Example |
|---|---|---|
| SUM | WorksheetFunction.Sum | .Sum(Range("B2:B9")) |
| AVERAGE | WorksheetFunction.Average | .Average(Range("B2:B9")) |
| MAX, MIN | WorksheetFunction.Max, .Min | .Max(Range("B2:B9")) |
| COUNTIF | WorksheetFunction.CountIf | .CountIf(Range("A2:A9"), "North") |
| SUMIF | WorksheetFunction.SumIf | .SumIf(Range("A2:A9"), "North", Range("B2:B9")) |
| VLOOKUP | WorksheetFunction.VLookup | .VLookup("BP-1040", Range("E2:F7"), 2, False) |
| MATCH | WorksheetFunction.Match | .Match("BP-1040", Range("E2:E7"), 0) |
In the VBA editor, typing the dot after WorksheetFunction brings up a list of the functions on offer. Not every Excel function is in it: for things VBA can already do itself, such as splitting text or taking the month from a date, use VBA directly. The next two lessons cover those.
Counting and adding by condition
For a summary by region, department or month, the loop runs over the list of groups, not over the data. CountIf and SumIf do the counting and adding in one go.
Task On the left are orders with region and amount; column D lists the regions for the summary. Write a macro Summarize that, for every region in column D (row 2 down to the last), writes the number of orders to column E with WorksheetFunction.CountIf and their total to column F with WorksheetFunction.SumIf.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Region | Amount | Region | Orders | Total | |
| 2 | North | 1,250.00 | North | |||
| 3 | South | 980.00 | South | |||
| 4 | North | 2,310.00 | West | |||
| 5 | West | 415.00 | ||||
| 6 | South | 1,720.00 | ||||
| 7 | North | 640.00 | ||||
| 8 | West | 1,985.00 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Looking things up: VLookup and error 1004
VLOOKUP in a cell shows #N/A when the lookup value is missing. In VBA, what happens depends on how you call the function:
| Call | When nothing is found |
|---|---|
WorksheetFunction.VLookup(…) | The macro stops with run-time error 1004. |
Application.VLookup(…) | It returns an error value and the macro carries on. IsError spots it. |
Dim price As Variant
price = Application.VLookup(Cells(r, 1).Value, Range("E2:F7"), 2, False)
If IsError(price) Then
Cells(r, 3).Value = "missing"
Else
Cells(r, 3).Value = price
End If
The variable has to be a Variant. A variable declared As Double cannot hold the error value, and the macro stops with "Run-time error '13': Type mismatch". The same goes for Application.Match. One downside of the short form: the editor shows no list of suggestions after Application. for these functions.
Task Write a macro GetPrices that, for every order (row 2 down to the last), looks up the item's price in the price list E2:F7 and writes it to column C. If an item is not in the price list, column C should say "missing". Use Application.VLookup and test the result with IsError.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Item | Qty | Price | Item | Price | |
| 2 | BP-1040 | 5 | OR-0815 | 2.45 | ||
| 3 | TN-2210 | 2 | BP-1040 | 3.99 | ||
| 4 | OR-0815 | 20 | KS-0400 | 0.79 | ||
| 5 | HN-3300 | 12 | TN-2210 | 77.90 | ||
| 6 | KS-0400 | 50 | HN-3300 | 1.99 | ||
| 7 | LC-0050 | 8.50 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
A function name that does not exist
Names have to match Excel's exactly. WorksheetFunction.Total makes the exercise report "Run-time error '438': Object doesn't support this property or method". Pick the name from the list the editor shows after the dot.
Forgetting WorksheetFunction
Range("E2").Value = Sum(Range("B2:B6")) makes VBA look for a procedure of your own called Sum. There is none, so you get "Compile error: Sub or Function not defined" before the macro even starts.
VLookup with no safety net
If an item is missing from the price list, WorksheetFunction.VLookup stops with "Run-time error '1004': Unable to get the VLookup property of the WorksheetFunction class", in Excel and in the exercise alike. On the visible data you may not notice, because every item is there. That is why Check tests with missing items.
Range without Set
rng = Range("B2:B9") without Set leads to "Run-time error '91': Object variable or With block variable not set". Ranges are objects and need Set.
Swapped arguments in SumIf
The order is criteria range, criteria, sum range, exactly as in the formula. Swap the two ranges and you compare amounts with region names: the result is 0, with no error message.
In real Excel
Sometimes a real formula in the cell is better than a fixed value: it recalculates when the data changes, and anyone can see where the number comes from. How a macro writes formulas into cells is shown in Write formulas. WorksheetFunction is the right choice when the macro keeps working with the result, in an If for example, or when only values should be left at the end.
FAQ
Can VLookup do an approximate match?
Yes, with True as the fourth argument, as in the formula. The first column then has to be sorted in ascending order. For price lists and item numbers, False is almost always what you want.
Is XLOOKUP available in VBA?
Yes, as WorksheetFunction.XLookup, but only in versions of Excel that have XLOOKUP as a formula (Microsoft 365, Excel 2021 and later). If the macro also has to run in older versions, use VLookup or Index with Match.
How do I catch the error from WorksheetFunction?
With error handling: On Error Resume Next before the call, then check Err.Number. That is covered in Error handling. To start with, Application.VLookup with IsError is simpler.
Can I test several conditions?
Yes, with CountIfs and SumIfs, just like COUNTIFS and SUMIFS. Ranges and criteria come in pairs.