You are on page 1of 12

T2-Lecture 1

Applications of
Information Technology

Introduction to VBA

The Fundamentals of User Defined Functions in VBA

AS1055 Lecture 1 (Term II)

Visual Basic for Applications (VBA)


Programming language used to write instructions in order
to create user specific applications in Excel
The main programming philosophy of VBA is based on
manipulating objects
VBA manipulates objects defined in the host application
For example, some of the main objects in Excel are related
to data analysis such as: worksheets, ranges, charts,
mathematical functions
Objects are further grouped in classes which interact in
strict hierarchy
e.g. Application <- Workbook <- Worksheet <- Chart,
whereas each of these object classes are themselves a
collection of many other objects
Each object contains also many properties and methods
that can manipulate them

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 2

1
T2-Lecture 1

Overview of the VBA Program Structure


Objects: programming models that are built around the
collection of properties that define a specific data
For example one can define a table object by the number of
rows, columns, headings and the type of data it holds
Code: program fragment that can be executed by VBA
Procedure: contains a group of codes that perform some
specific action.
There are two main types of VBA procedures:
Functions: return a single value (or many values stored in
arrays). For example:
1. Function ArootB(A, B) 2. Function GetFormula(Cell)
ArootB = B^(1/A) GetFormula = Cell.Formula
End Function End Function
Then an Excel cell formula like: =ArootB(2, 25) 5
=GetFormula(A2) =ArootB(2,25)
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 3

Overview of VBA Program Structure (2)


Sub(routines) : a collection of program codes,
statements or functions that can be executed to
complete an action. For example:
3. Sub Test()
ret= ArootB(2,25)
MsgBox The square root of 25 is & ret
Application.ActiveCell.Value = ret
End Sub
The ret variable is only available to this procedure and its value is
not returned. Then running this subroutine brings up the pop-up
window and also places the value of ret in the active cell.
Modules: files that can be stored in an Excel WB, which
contain the codes and procedures that make up the VBA
program. Modules can be added to a WB and edited using
the VB Editor (VBE)
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 4

2
T2-Lecture 1

The Basics of VBE


VBA programs can be written, ran (executed) and
edited/debugged using the Visual Basic Editor (VBE)
The VBA programs that are part of an Excel WB are
running in the background and can only be seen
through VBE
Excel WB that contains a VBA program can only be
saved as an Excel Macro-Enabled WB (.xlsm)
By default, the VBE related menus are not shown in the
Excel 2010/13 Ribbon. To activate them one needs to
change the Excel Options settings:
(Office ) File Options Customize Ribbon
(Select the Developer check box under the Main Tabs)

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 5

The Basics of VBE (2)

Then from Excel the VBE can be activated by:


1. Developer Visual Basic ; or Controls View Code
2. Press Alt+F11 keyboard shortcut
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 6

3
T2-Lecture 1

Excel Button
(Alt+F11) The Basics of VBE (3)

Project
Explorer Module
Window

Properties
Window

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 7

The Basics of VBE (4)


The Project Explorer
Every VBA program associated to a WB is treated as a
project, which is organised in Excel objects, Modules and
Forms (displayed as required by an expandable tree
structure)
VBA modules
The main programs are stored in Modules
A module can be added by Insert Module
A module can be removed by File Remove Modulexx
(It is possible to export (save) the module (file) before removing it)
It is possible to insert code into a VBA module in one of the
following ways:
Manually (type from the keyboard)
Copy and Paste
Use the macro-recorder utility of Excel (for macros only!)

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 8

4
T2-Lecture 1

Creating Function Procedures


A function is a VBA procedure that carries out some
calculations (possibly on the arguments) and returns a
value (or an array of values)
These are often referred to as User Defined Functions
(UDF)
The main reason to create a UDF is to automate the
WB programs and to eliminate very long, cumbersome
or nested WS function (WSF) formulas
UDF can perform important intermediary steps within
a longer VBA program that can eliminate the need to
duplicate code (i.e. when the same procedure needs to
be repeated in many different places of the code)
Warning: Avoid reinventing the wheel though!
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 9

Creating Function Procedures (2)


Syntax for declaring a UDF is as follows:
Function name ([arglist] [As type]) [As type]
[comments]
[instructions]
name= expression
[Exit Function]
[instructions]
[name= expression]
End Function
In addition, the Function might be given a clear scope:
[Public | Private]
The syntax elements shown in bold are compulsory as
they appear here (filled in automatically by VBE as you
type). The values in [] are optional.
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 10

5
T2-Lecture 1

Creating Function Procedures (3)


Where the UDF components are:
name : a valid function procedure name
arglist : list of valid argument names that can be passed
on to the function (separated by commas)
type : argument/variable type that the function can
make use of (or it will return)
comments : brief comments (preceded by an apostrophe)
instructions : any number of valid VBA statements
(commands)
Exit Function : optional command that forces the
termination of the function before completion (the value
of name prior of this statement will be returned)

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 11

Creating Function Procedures (4)


General Rules:
Each statement must be on a separate line
Longer statements can be broken up in shorter segments
between objects (names, arguments, etc.) using _
(i.e. space-underscore-enter, without the quotation
marks, which are used here only for display)
The function statements are executed in a top-to-bottom
left-to-right order, unless they contain branching and/or
looping structures (will be covered later in the module)
The = is the assignment operator that replaces the
value of the variable (object) on the LHS with the value
on the RHS. To the name value must be assigned at least
once a valid VBA expression.
When the End/Exit Function statement is reached, the
last value assigned to the name variable is returned
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 12

6
T2-Lecture 1

Creating Function Procedures (5)


Naming Rules:
A function/variable name must begin with a letter
Names cannot contain special characters like:
spaces, ., :, ;, $, #, @, ..., etc.
Names should not be identical to built-in Excel/VBA
function or object names
A VBA function that is also intended to be used as
WSF should not be named as a single letter or a
combination of letters and numbers that could also
represent a cell/range address (or name) e.g. A5()
It is helpful to use names as meaningful as possible
(that reflects the purpose of the function)
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 13

Creating Function Procedures (6)


Examples of functions with argument(s):
1. Function Fun(x)
Application:
Fun = x*100 + x*10 + x
End Function =Fun(5) 555
2. Function AtoB(A, B)
A^B . The same as =POWER() WSF
Note: comments are not executed
AtoB = A^B =AtoB(3,4) 81
End Function

3. Function AreaCirc(diam)
AreaCirc = 0.7854 * diam^2 =AreaCirc(5)
End Function 19.635
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 14

7
T2-Lecture 1

Creating Function Procedures (7)


Examples of functions with argument(s):
4. Function Funy(x, y, z)
Application:
Funy = x*100 + y*10 + z
End Function =Funy(5,6,7) 567
5. Function Lin(x, a, b)
Returns a linear function at point x
Lin = a*x + b
=Lin(15, 0.5, -3) 4.5
End Function

6. Function Quad(x, a, b, c)
Returns a quadratic function at point x
Quad = a*x^2 + b*x + c
End Function
=Quad(5.1, 1, -1.2, 2)
21.89
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 15

Creating Function Procedures (8)


Examples of functions without argument:
These functions often read application or
system properties and return some information
1. Function User()
Application:
Returns the current Excel user name
User = Application.UserName
=User() zoli
End Function

Note in the above example, the object Application is


used which contains (amongst many other) the object
property UserName.
The hierarchy levels are separated by a dot.
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 16

8
T2-Lecture 1

Creating Function Procedures (9)


Examples of functions without argument:
2. Function WsName()
Returns the current worksheet name:
Application:
WSName = Application.ActiveSheet.Name
End Function
=WsName() Sheet1
3. Function qtrpi()
qtrpi = Application.WorksheetFunction.Pi() / 4
End Function =qtrpi() 0.78534
4. Function AreaCirc2(diam)
AreaCircle2 = qtrpi() * diam ^ 2 =AreaCirc2(10)
End Function
78.54
Note that in this version of AreaCirc2(), the function
makes use of (i.e. calls) the previous function qtrpi().
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 17

Creating Function Procedures (10)


Examples of functions that are emulating Excel WS
functions:
1. Function Roundws(val, dec)
Roundws = Application.WorksheetFunction.Round(val, dec)
End Function
Then a call like =Roundws(qtrpi(), 4) 0.7854
Note that all the Excel WS functions can be called through the
WorksheetFunction property of Application that returns any WSF
method (e.g. Round). Thus, the syntax for WS functions in VBA is:
Application.WorksheetFunction.WSFName(arglist)
where WSFName is the name of the WS function and arglist is the
corresponding list of arguments.

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 18

9
T2-Lecture 1

Creating Function Procedures (11)


Examples of functions that are emulating Excel WS
functions:
2. Function SSq(x, y, z)
x = x^2 x value is changed
y = y^2 y value is changed
z = z^2 z value is changed
Observe that the argument values only inside
the function have been changed. This do not
affect the original values used in the call
SSq = Application.WorksheetFunction.Sum(x, y, z)
End Function
Then a call like =SSq(A48, B48, C48) 35
where the values in cells A48:C48 are 1, 3 and 5, respectively.
These cell values do not change following a call to SSq() !

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 19

Creating Function Procedures (12)


Examples of functions that are using built in VBA
functions:
Just like in the case of WSF, there are many ready-made VBA
functions available to be used in the UDF. Note, however, that
these are often named differently from the corresponding WSF:
1. Function SSqr(x, y, z)
x = sqr(x) square root of x
y = sqr(y) square root of y
z = sqr(z) square root of z
sqr() function is equivalent to SQRT() Excel WSF
SSqr = Application.WorksheetFunction.Sum(x, y, z)
End Function
Then a call like =SSqr(1, 9, 25) 9
T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 20

10
T2-Lecture 1

Creating Function Procedures (13)


A detailed list of VBA functions with full
description and help is made available online by
Tech on the Net organisation at:

By categories (e.g. text, numerical, logical, etc)


http://www.techonthenet.com/excel/formulas/index_vba.php

By alphabetical list
http://www.techonthenet.com/excel/formulas/index_vba_alpha.php

T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 21

VBA functions (By Category)

Source: TECH on the Net


T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 22

11
T2-Lecture 1

VBA functions (Alphabetically)

Source: TECH on the Net


T2-Week 1 IT Applications - Lecture 1: Introduction to VBA 23

12

You might also like