You are on page 1of 4

City Short Courses

VBA for Microsoft Excel – Functions


Table of Contents
Function AreaCircle(rad as Single) As Single
1 Creating User Defined Functions ................................................................ 1 AreaCircle = 3.14159 * rad * rad 'this line returns the value
1.1 The Function Declaration .................................................................... 1 End Function
1.2 Defining a function ............................................................................... 1
The calculation in the body of the function uses the argument that must be
1.3 Testing the function.............................................................................. 1
supplied to it, i.e., rad – a variable here is not necessary.
1.4 Using the function on a worksheet .................................................... 1
1.5 A function to calculate NetPay ........................................................... 2 The whole point of a function is to return a value; therefore the function must
2 WorksheetFunction method ......................................................................... 3 include a line somewhere that does this. In the above example that line is
3 VBA functions ................................................................................................ 3 AreaCircle = 3.14159 * rad * rad
It is essential to note that the return value must be the same word as the
function name, i.e., AreaCircle
1.3 Testing the function
1 Creating User Defined Functions You can test the function in the Immediate window before you attempt to use
There are two types of procedure –Subs and there are also Functions. The it, e.g., ?AreaCircle(10)
characteristic feature of a function is that it returns a value to the location The example is supplying 10 as the argument, so the function returns the area
where the function is called. Secondly, if you create a function you can use it of a circle with radius 10
on the worksheet as a formula.
1.4 Using the function on a worksheet
1.1 The Function Declaration You cannot run a function in the same way you would run a Sub (e.g., [F5]
The opening line is called the function declaration. For example the first line of doesn’t work). You must call it. You can directly use it in a formula:
a function to find the area of a circle might look like: Type ‘=AreaCircle( ‘ into a cell, click a cell that contains a number , then
click the Enter button (the tick)
Function AreaCircle(rad as Single) As Single

Argument data type of argument data type of return value

1.2 Defining a function


The whole function might look like:

Page 1 of 4
City Short Courses

NetPay is how much you take home after IncomeTax, National Insurance and
Or from the Formulas tab,
Pension Fund contributions have been deducted.
choose the InsertFunction
button, The arithmetic would look like this in code:
Deductions = (GrossPay * IncomeTax) _
choose UserDefined + (GrossPay * NI) _
+ (GrossPay * Pension)
from the dropdown, NetPay = GrossPay - Deductions
select the function
from the list and The full function would look like this:
click OK
Function NetPay _
(GrossPay As Single, IncomeTax As Single, _
NI As Single, Pension As Single) As Single
Dim Deductions As Single
Deductions = (GrossPay * IncomeTax) + _
In the next step click in the textbox and click the cell that contains the radius, (GrossPay * NI) + _
then click OK (GrossPay * Pension)
NetPay = GrossPay - Deductions
End Function

Note that NetPay is the return value for the function and the function name.
1. To insert the function, select a cell and choose the Insert Function icon
from the Formulas tab
2. Choose the User Defined category and select NetPay and click OK
3. Put the cell references into the textboxes and click OK

1.5 A function to calculate NetPay


Let's say you want to create a function that calculates how much your Net Pay
is after deductions. The function would involve these values:
 GrossPay: how much you earn before deductions
 Income Tax as a percentage
 National Insurance as a percentage
 Pension Fund as a percentage

Page 2 of 4
City Short Courses

As another example, you could write a function which named PriceChange You can make use of the Union operator (,) with the arguments to the function
to calculate the percentage change in a share price. The function might look as ActiveCell = WorksheetFunction.Average(Range(“B2:B9”), Range(“D2:D9”))
follows: The limitation with WorksheetFunction is that the functions don’t recalculate
Function PriceChange (opening As Single, closing As Single) unless you re-run the macro - for dynamic data, it is better to use Excel’s
As Single formulas. On the other hand these statements are quicker to run than a
PriceChange = (closing - opening) / opening solution that uses loops
End Function
You might put the return value into a variable e.g.,
It really doesn’t matter what you call the arguments, as long you use them in a variable = WorksheetFunction.Sum(Selection)
way that is consistent with the logic of the function. However the variable
Sub SumNumbersInSelection()
containing the return value must have the same name as the Function itself. Dim Total As Single
You can type the function into the Excel interface like so: Total = WorksheetFunction.Sum(Selection)
Range(“C12”) = Total
MsgBox "The sum of numbers in the selection is " _
& Total
End Sub

3 VBA functions
VBA provides many inbuilt functions, some of which are the same as in Excel. Here is
a selection.

Mathematical functions Example


Abs() returns absolute value of numeric field Abs(-1234.5) returns
1234.5
Int() returns numeric value with the decimal Int(13.9) returns 13
fraction discarded
The above way is the same as using an Excel pre-defined function. Round() returns a number rounded to a specified round(12.459, 2)
number of decimal places. syntax is: returns 12.46
2 WorksheetFunction method Round(expression, numdecimalplaces)
where the numdecimalplaces argument is round(12.9)
If you want to use Excel’s worksheet functions in your code, the returns 13
optional; the function returns an integer if it is
Application has a WorksheetFunction method. The syntax is:
Application.WorksheetFunction.FunctionName(arg1,arg2)
omitted.
Rnd() creates random number (single) between 0 and to generate a random
where FunctionName is the name of an Excel function. (You can drop 1 whole number between
Application from the reference) For example, 0 and 9 you can use:
ActiveCell = WorksheetFunction.Average(Range(“B2:B9”)) or Int(Rnd()*10)
Other maths functions are: Atn , Cos , Exp, Log, Sgn, Sin, Sqr, Tan
ActiveCell = WorksheetFunction.Max(Worksheets(“Exams”).Range(“C6:C22”))
Range(“B10”) = WorksheetFunction.Average(Selection)

Page 3 of 4
City Short Courses

VBA Date and Time functions VBA Text manipulation functions


Function Description Example (You can use # instead of “) Example
Date() or returns the current Date() LCase() returns lower case version LCase(“ABCD”)
Now() system date of a string
Day() returns an Integer Day(“31-Jan-2004”) UCase() returns upper case version UCase(“abcd”)
representing the day returns 31 of a string
from a Date value Trim() removes leading and trailing Trim(“ ABC “)
Month() returns an Integer that Month(“31-Jan-2004”) spaces from a string
represents the month of returns 1 LTrim() removes leading spaces LTrim(“ ABC”)
a Date value from a string
Year() returns an Integer that Year(“31-Jan-2004”) RTrim() removes trailing spaces RTrim(“ABC “)
represents the year of a returns 2004 from a string
Date value Len() returns number of Len(“Manchester”)
Weekday() returns day of the week Weekday(“31/01/2004”) characters in a string returns 10
(Sunday = 1) returns 7 Left() returns leftmost characters Left(“Manchester”,4)
DateAdd() returns a data to which DateAdd("yyyy", 1, date()) of a string returns Manc
a specified time interval returns the date 1 year from today Right() returns rightmost characters Right(“ABCDEF,3”)
has been added; all DateAdd("ww", -3, ”4 Mar 2004”) of a string returns DEF
three arguments are returns the date 3 weeks earlier than 4th Mid() returns characters within a Mid("Lindsey Davenport",9,4)
required March 2004 string returns Dave i.e. start at the 9th
DateDiff() returns an Integer DateDiff(“d”, Date(), ”31-Jan-2004”) character and return a string 4
representing the returns the number of days between 31-Jan- characters long
difference between two 2004 and the current date StrComp() compares two strings for StrComp(“ABC,”abc”)
dates equivalence and returns the returns 1 (strings are not considered
DateSerial() returns a date given DateSerial(2004, 1,31) integer result of to be the same)
three integers returns 31/01/2004 comparison: 0 if strings are StrComp(“ABC,”abc”,vbTextCompare)
that specify year, equal, -1or 1 if strings are returns 0 (strings are are considered to
month, day in that order different be the same; vbTextCompare performs
case insensitive comparison)
StrConv converts the case of a string StrConv(“london”, vbProperCase)
returns “London”
you could also use vbUpperCase and
vbLowerCase for the conversion
argument
Val() returns numeric value of a Val(“123.45”)
string

Page 4 of 4

You might also like