How to Use VBA Worksheet Functions in Excel 2016
Although VBA offers a decent assortment of built-in functions, you might not always find exactly what you need. Fortunately, you can also use most of Excel’s worksheet functions in your VBA procedures. The only worksheet functions that you cannot use are those that have an equivalent VBA function. For example, you can’t use Excel’s RAND function (which generates a random number) because VBA has an equivalent function: Rnd.
VBA makes Excel’s worksheet functions available through the WorksheetFunction object, which is contained in the Application object. Here’s an example of how you can use Excel’s SUM function in a VBA statement:
Total = Application.WorksheetFunction.SUM(Range(“A1:A12”))
You can omit either the Application part or the WorksheetFunction part of the expression. In either case, VBA figures out what you’re doing. In other words, these three expressions all work exactly the same:
Total = Application.WorksheetFunction.SUM(Range(“A1:A12”)) Total = WorksheetFunction.SUM(Range(“A1:A12”)) Total = Application.SUM(Range(“A1:A12”))
My personal preference is to use the WorksheetFunction part just to make it perfectly clear that the code is using an Excel function.
Worksheet function examples
Here, you discover how to use worksheet functions in your VBA expressions.
Finding the maximum value in a range
Here’s an example that shows how to use Excel’s MAX worksheet function in a VBA procedure. This procedure displays the maximum value in column A of the active worksheet:
Sub ShowMax() Dim TheMax As Double TheMax = WorksheetFunction.MAX(Range(“A:A”)) MsgBox TheMax End Sub
You can use the MIN function to get the smallest value in a range. And as you might expect, you can use other worksheet functions in a similar manner. For example, you can use the LARGE function to determine the kth-largest value in a range. The following expression demonstrates this:
SecondHighest = WorksheetFunction.LARGE(Range(“A:A”),2)
Notice that the LARGE function uses two arguments. The second argument represents the kth part — 2, in this case (the second-largest value).
Calculating a mortgage payment
The next example uses the PMT worksheet function to calculate a mortgage payment. Three variables are used to store the data that’s passed to the Pmt function as arguments. A message box displays the calculated payment.
Sub PmtCalc() Dim IntRate As Double Dim LoanAmt As Double Dim Periods As Long IntRate = 0.0625 / 12 Periods = 30 * 12 LoanAmt = 150000 MsgBox WorksheetFunction.PMT(IntRate, Periods, -LoanAmt) End Sub
As the following statement shows, you can also insert the values directly as the function arguments:
MsgBox WorksheetFunction.PMT(0.0625 /12, 360, -150000)
However, using variables to store the parameters makes the code easier to read and modify, if necessary.
Using a lookup function
The following example uses VBA’s InputBox and MsgBox functions, plus Excel’s VLOOKUP function. It prompts for a part number and then gets the price from a lookup table. Below, range A1:B13 is named PriceList.
Sub GetPrice() Dim PartNum As Variant Dim Price As Double PartNum = InputBox(“Enter the Part Number”) Sheets(“Prices”).Activate Price = WorksheetFunction.VLOOKUP(PartNum, Range(“PriceList”), 2, False) MsgBox PartNum & “ costs “ & Price End Sub
Here’s how the GetPrice procedure works:
VBA’s InputBox function asks the user for a part number.
The part number the user enters is assigned to the PartNum variable.
The next statement activates the Prices worksheet, just in case it’s not already the active sheet.
The code uses the VLOOKUP function to find the part number in the table.
Notice that the arguments you use in this statement are the same as those you would use with the function in a worksheet formula. This statement assigns the result of the function to the Price variable.
The code displays the price for the part via the MsgBox function.
This procedure doesn’t have any error handling, and it fails miserably if you enter a nonexistent part number. (Try it.) If this were an actual application that’s used in an actual business, you would want to add some statements that deal with errors more gracefully.
Entering worksheet functions
You can’t use the Excel Paste Function dialog box to insert a worksheet function into a VBA module. Instead, enter such functions the old-fashioned way: by hand. However, you can use the Paste Function dialog box to identify the function you want to use and find out about its arguments.
You can also take advantage of the VBE’s Auto List Members option, which displays a drop-down list of all worksheet functions. Just type Application.WorksheetFunction, followed by a period. Then you see a list of the functions you can use. If this feature isn’t working, choose the VBE’s Tools → Options command, click the Editor tab, and place a check next to Auto List Members.
More about using worksheet functions
Newcomers to VBA often confuse VBA’s built-in functions and Excel’s workbook functions. A good rule to remember is that VBA doesn’t try to reinvent the wheel. For the most part, VBA doesn’t duplicate Excel worksheet functions.
For most worksheet functions that are unavailable as methods of the WorksheetFunction object, you can use an equivalent VBA built-in operator or function. For example, the MOD worksheet function is not available in the WorksheetFunction object because VBA has an equivalent: its built-in Mod operator.
Bottom line? If you need to use a function, first determine whether VBA has something that meets your needs. If not, check out the worksheet functions. If all else fails, you may be able to write a custom function by using VBA.