Write your own functions in VBA

Some calculations come up again and again, yet Excel has no ready-made function for them: a gross amount with rounding, a customer class based on sales, initials from a name. With Function you write them once and then use them in any cell and any macro.

In short: a function starts with Function Name(argument As Type) As Type and ends with End Function. You set the return value with Name = …. In a cell you use it like any Excel function (=Gross(B2,$F$1)), in a macro with parentheses: x = Gross(100, 0.2).

What you need to know: If Then Else and string functions.

Try it right now

A ready-made macro puts the formula into column C, just as you would type it by hand. Only the function itself is missing. As long as it does not exist, Excel shows #NAME? in those cells. Write the function at the top of the code and the cells start calculating.

Task The macro FillFormulas is already done: it writes the formula =Gross(B2,$F$1) into column C, just as you would type it by hand. The function Gross is missing. Write it: it takes the net amount and the tax rate and returns the gross amount, rounded to 2 decimal places (Round). Check also tests it with a different tax rate in F1.

ABCDEF
1ItemNetGrossTax rate20.00%
2Office chair249.00
3Desk389.50
4Drawer unit129.90
5Monitor arm74.99
6Floor lamp58.00

How a function is built

Function Gross(net As Double, rate As Double) As Double
    Gross = Round(net * (1 + rate), 2)
End Function
PartMeaning
Function GrossStart and name. This is the name you use in cells and macros.
(net As Double, rate As Double)The arguments. With =Gross(B2,$F$1), net gets the value from B2 and rate the value from F1.
As Double after the parenthesesThe type of the return value, here a number with decimals. For text, As String.
Gross = …Assigning to the function's name decides what comes back.
End FunctionEnd of the function.

The difference from a Sub: a Sub does something, a Function returns a value. That is why a Function does not show up under Developer > Macros, but it does appear in the Insert Function dialog, in the "User Defined" category.

Functions in a cell

A function in a normal module can be used in any cell of the workbook, with commas between the arguments like any other formula. When an argument changes, the cell recalculates. A function used in a cell may only return a value: it cannot write to other cells, change formats or add sheets while it does so.

Calling a function from a macro

In a macro you call the function with parentheses and use the result like any value. The rule lives in one place in your code, and the Sub only deals with the rows:

Cells(r, 3).Value = CustomerClass(Cells(r, 2).Value)

Task Write a function CustomerClass that returns the class for an annual sales figure: "A" from 10,000, "B" from 5,000, "C" below that. The macro Classify should call the function for every row from 2 and write the result to column C.

ABCD
1CustomerAnnual salesClass
2Carter Ltd18,400.00
3Hughes and Sons4,200.00
4Wolf Bakery9,800.00
5Rivera Print10,000.00
6Shaw Optics2,750.00
7Baker and Co5,000.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.

Find the bug

A mistake almost everyone makes once, and one VBA shows no message for:

Task Find the bug: the function Initials should turn "First Last" into initials (Emily Carter becomes EC), and the macro FillInitials writes them to column B. The macro runs without an error message, but column B stays empty even though the calculation inside the function is right. Get it working.

ABCD
1EmployeeInitials
2Emily Carter
3Daniel Hughes
4Grace Okafor
5Megan Lloyd
6Luis Ramirez

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

The return value is never assigned

If the function calculates into a helper variable but never assigns anything to its own name, it returns the default value: 0 for numbers, empty text for String. There is no error message; the cells just stay empty or show 0. The exercise reports: "B2 is empty, expected: „EC“."

#NAME? in the cell

Excel does not know the function. Typical causes: a typo in the name, the function sits in a worksheet's code window instead of a module, or it says Sub instead of Function. Also check that the workbook with the macros is open.

Calling without parentheses

Cells(r, 3).Value = CustomerClass Cells(r, 2).Value without parentheses confuses VBA, which reports "Compile error: Expected: end of statement". When you need the return value, the arguments go in parentheses.

Conditions in the wrong order

If the function tests sales >= 5000 first and >= 10000 second, a customer with 18,400 is caught by the first test and gets "B". The exercise reports: "C2 contains „B“, expected: „A“." With thresholds, always start with the highest.

In real Excel

  1. Insert a module: in the VBA editor (Alt+F11), Insert > Module. Only functions in a module like this can be used in cells.
  2. Write the function and switch back to Excel.
  3. Use it in a cell: type =Gross(B2,$F$1). Excel suggests the name as you type, just as it does for built-in functions.
  4. Save as .xlsm: without the macros in the file, the cells show #NAME? next time. Whoever receives the file has to allow macros; see Enable macros.

FAQ

Why does my function not recalculate when a cell changes?

Excel recalculates a cell with your function when one of its arguments changes. If the function reads other cells directly with Range, Excel does not notice. So pass everything the function calculates with as an argument.

Can I use the function in every workbook?

Yes, if you save it in an add-in (.xlam) and switch the add-in on under File > Options > Add-ins. The Personal Macro Workbook works too, but then the cell needs the file name in front of the function name.

Can a function have several or optional arguments?

Yes, as many as you like, separated by commas. With Optional in front, an argument can be left out when calling. More in Procedures and arguments.

Does this work in Excel for the web?

No. Excel for the web does not run VBA macros, and that includes your own functions.

Up next: project monthly report

To finish level 3 you build a monthly report: one sheet per region, totals, formats and a summary with shares.

Go to the project

Write to us

Choose language

Select your preferred language