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.

ABCDE
1BranchSalesMeasureValue
2Leeds48,200.00Total
3Bristol39,750.00Average
4Austin27,400.00Highest
5Denver31,980.00
6Glasgow35,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.

FormulaVBAExample
SUMWorksheetFunction.Sum.Sum(Range("B2:B9"))
AVERAGEWorksheetFunction.Average.Average(Range("B2:B9"))
MAX, MINWorksheetFunction.Max, .Min.Max(Range("B2:B9"))
COUNTIFWorksheetFunction.CountIf.CountIf(Range("A2:A9"), "North")
SUMIFWorksheetFunction.SumIf.SumIf(Range("A2:A9"), "North", Range("B2:B9"))
VLOOKUPWorksheetFunction.VLookup.VLookup("BP-1040", Range("E2:F7"), 2, False)
MATCHWorksheetFunction.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.

ABCDEF
1RegionAmountRegionOrdersTotal
2North1,250.00North
3South980.00South
4North2,310.00West
5West415.00
6South1,720.00
7North640.00
8West1,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:

CallWhen 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.

ABCDEF
1ItemQtyPriceItemPrice
2BP-10405OR-08152.45
3TN-22102BP-10403.99
4OR-081520KS-04000.79
5HN-330012TN-221077.90
6KS-040050HN-33001.99
7LC-00508.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.

Learn this next: string functions

Left, Mid, InStr, Replace and Split: split names, clean up item numbers and build email addresses.

Learn string functions

Write to us

Choose language

Select your preferred language