Skip to content

Write your own worksheet function

Dialogs, functions and events9 minPremium

Builds on Make decisions with If and Select Case.

A finance team in Omaha reports by fiscal quarter, and their fiscal year starts on July 1. Every workbook repeats the same long formula to turn a date into Q1 to Q4, and every copy is a chance for a typo.

How it works

A Function procedure is a macro that hands back a value. Write it in a module (Insert > Module in the VB Editor), and it works in a cell like a built-in function: =FiscalQuarter(A2).

  • The arguments go in brackets after the name, each with its type.
  • As after the brackets gives the type of the result.
  • The function returns its result by assigning it to its own name.

The function appears in Insert Function under User Defined, and Excel works it out again whenever the cells you give it change.

Example

VBA
Function FiscalQuarter(d As Date) As String
Dim m As Long
m = Month(d)
If m >= 7 Then
FiscalQuarter = "Q" & (m - 7) \ 3 + 1
Else
FiscalQuarter = "Q" & (m + 5) \ 3 + 1
End If
End Function
Turns a date into its fiscal quarter, for a year that starts on July 1: July to September is Q1.

\ divides and drops the remainder. For a date in August, month 8, (8 - 7) \ 3 + 1 is 1, so the cell shows Q1; for February, (2 + 5) \ 3 + 1 is 3, so Q3.

A function used in a cell can only return a value. It can't change other cells, formats or sheets, and a line that tries makes the cell show #VALUE!. The workbook that holds the function must be open, or the cells that use it show #NAME?, so keep it in the workbook that uses it, saved as .xlsm.

Common mistakes

  • Calculating the result into a variable and never assigning it to the function's name. The cell shows 0, or an empty result.
  • Writing the function in a sheet module or ThisWorkbook. Cells can't find it there, and show #NAME?; put it in a module.
  • Writing it as a Sub. A Sub can't return a value, so it never appears in a cell.

In short

  • Function Name(argument As Type) As Type ... End Function, in a module.
  • Assign the result to the function's name.
  • A function in a cell returns a value and changes nothing else.

Practice

Premium

4 exercises: 3 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.