You are on page 1of 31

Chapter 36: User-Defined Function with VBA

1. Overview
Visual Basic for Applications (VBA) provides a complete programming language and environment fully
integrated with Excel and all other Microsoft Office applications.

In this chapter, we introduce user-defined functions

The examples and screen shots depict the Excel 2019 working environment but are fully compatible with
all version of Excel using Visual Basic for Applications

Pic

2. Using the VBA Editor to Build a User-Defined Function


A user function is a saved list of instructions for Excel that produces a value. Once defined, a user
function can be used inside an Excel worksheet like any other function.

User-defined functions are usually attached to a specific workbook and are only available if that
workbook is currently open in Excel. If you want a macro to be available whenever you use Excel on a
specific computer save it in the Personal Macro Workbook; see Chapter 35, section16.

Activate the VBA editor by:

 Using the keyboard shortcut [Alt]+F11


 From the Excel ribbon (Developer Tab – Visual Basic Editor)

To show the Developer tab, go to File – (More) - Options – Customize the Ribbon and indicate Developer
The result is a new window like the following screen shot

A user-defined function needs to be wriitten in a module

Open a new module, select Insert – Module from the menu in the VBA editor environment

This will open a new window:


The first function (named “plus”) written will add together two number

A user-defined function in Excel has three obligatory elements:

1. A header line with the name of the function and a list of parameters.

2. A closing line (usually inserted by VBA).

3. Some program lines between the header and the closing line.
Start writing the 1st line
function plus (parameter1,parameter2)

As soon as you end the line with a tap on the Enter key, the closing line for the function will be inserted,
and the cursor will be in position between the header and the closing line ready for you to go on typing.

We type the function line – the line that make our function do something. Our first function will take 2
variables and return their sum
plus = parameter1 + parameter2
3. Providing Help for User-Defined Function in the Function Wizard
Excel’s Function Wizard (shown below) provides a short help line (an explanation of what the function
does).
To attach a text description to our function, activate the macro selection box. You can do this either
from the Excel ribbon (Developer|Macros) or by using the keyboard shortcut [Alt] + F8

Click in the Macro name box, and type the name of the function

Click on the Option button

Type the description in the Description box. Click OK and close the macro selection box
4. Saving Excel Workbook with VBA Content
When you first try to save a workbook with VBA content, Excelwill present you with the following
message:
You should choose No and get the Save As dialog to enable you to choose a new file type.

Open the circled selection, select the second option Excel Macro-Enabled Workbook (xlsm) and save the
workbook.

5. Fixing mistakes in VBA


Mistake 1: Using the Wrong Syntax
Writing Plus you forget the “+” between parameter1 and parameter2. When you hit Enter, you get the
message:

Click OK and correct this mistake

Mistake 2: Right Syntax with a Typing Error


In this case we define two functions—function1 and function2. Unfortunately, the program line for
function2 mistakenly calls the function “function1”

Click OK and correct the mistake

We can (and should) have VBA check the module for errors before trying to use the functions in the
module. From the VBA menu we select Debug - Compile VBAproject

6. Conditional Execution: Using If Statement in VBA Function


 The One-Line if Statement

The simplest way to control the execution of a VBA function: One statement is executed if a condition is
true and another is executed if a condition is not true.

The complete condition and its statement should be on one line

Ex:
Function OneLineIf(Parameter)
If Parameter > 5 Then OneLineIf = 1 Else OneLineIf = 15
End Function
This means when parameter > 5 in this case is 12, onelineif returns 1 and when parameter < 5 in the
cases is 3, onelineif returns 15

The one-line If statement doesn’t even need the Else part.

Function OneLineIf1(Parameter)
If Parameter > 5 Then OneLineIf1 = 1
End Function

This means when parameter > 5 in this case is 12, onelineif1 returns 1 and when parameter < 5 in the
case is 3, onelineif1 returns 0
You can assign a value to your function first

Function OneLineIf2(Parameter)
OneLineIf2 = -15
If Parameter > 5 Then OneLineIf2 = 1
End Function
This means when parameter > 5 in this case is 12, onelineif2 returns 1 and when parameter < 5 in the
cases is 3, onelineif2 returns -15

 If…ElseIf Statement

If more than one statement is to be conditionally executed, the block If…ElseIf statement can be used. It
uses the following syntax:

If Condition0 Then
Statements
ElseIf Condition1 Then
Statements
Else
Statements
End If

The Else and ElseIf clauses are both optional. You may have as many ElseIf

clauses as you want following an If, but none can appear after an Else clause.

If statements can be contained within one another.

Function BlockIf(Parameter)
If Parameter < 0 Then
BlockIf = -1
ElseIf Parameter = 0 Then
BlockIf = 0
Else
BlockIf = 1
End If
End Function
In this example, you can see that if:

 Parameter = -3 (<0) then blockif return -1


 Parameter = 0 (=0) then blockif return 0
 Parameter = 5 (>0) then blockif return 1
 Nested if

If statements can be used as part of the statements used in another If statement. A program structure
that has some If statements inside others is called a nested If structure. Each If statement in the
structure must be a complete If statement. Either the one-line or the block version can be used.
Function NestedIf(P1, P2)

If P1 > 10 Then
If P2 > 5 Then NestedIf = 1 Else NestedIf = 2
ElseIf P1 < -10 Then
If P2 > 5 Then
NestedIf = 3
Else
NestedIf = 4
End If
Else
If P2 > 5 Then
If P1 = P2 Then NestedIf = 5 Else NestedIf = 6
Else
NestedIf = 7
End If
End If
End Function
Explanation:

If P1=11 (>10)

 P2=6 (>5) then nestedif=1


 P2=3 (<5) then nestedif=2

If P1=-22 (<-10)
 P2=6 (>5) then nestedif=3
 P2=4 (<5) then nestedif=4

If P1=6 (<10)

 P2= 6 (>5) And if P1=P2=6 then nestedif=5

If P1=-5 (<10)

 P2=7 (>5) And P1 different from P2 (-5 different from 7) then nestedif=6

If P1=4 (<10)

 P2=3 (<5) then nestedif = 7

7. The Boolean and Comparison Operators


The expressions used as conditions in an If statement are also known as Boolean expressions.

Boolean expressions can have one of two values:

 TRUE when the condition holds


 FALSE when the condition is violated.

Usually Boolean expressions are constructed using the Comparison and/or Boolean operators.

List of common Comparison operators

 The And Boolean Operator

The next function uses a Boolean operator to check whether two conditions hold at the same time.

Function AndDemo(parameter1, parameter2)


If (parameter1 < 10) And (parameter2 > 15) _
Then
AndDemo = 3
Else
AndDemo = 12
End If
End Function
It checks both condition (parameter 1<10 and parameter 2 >15)

If both conditions are hold, anddemo returns 3

Otherwise, anddemo returns 12

 The Or Boolean Operator


checks whether at least one of two conditions holds

Function OrDemo(parameter1, parameter2)


If (parameter1 < 10) Or (parameter2 > 15) _
Then
OrDemo = 3
Else
OrDemo = 12
End If
End Function
It checks whether either 1st condition (parameter1 <10) or 2nd condition (parameter2>15) or both
conditions hold

Only if both conditions are violated, ordemo returns 12. Otherwise, it returns 3.

8. Loops
Are used when you need to do something repeatedly.

There are two major looping constructs:

 Top-checking loop: The loop condition is checked before anything else gets done. Ex: Do While;
Do Until
 Bottom-checking loop: The loop condition is checked after the something to be done is done. Ex:
Do…LoopWhile; Do…LoopUntil

The function used is defined as:

f ( 0 )=1 f ( 1 )=1 f ( 2 )=2∗f ( 1 )=2 f ( n )=n∗f (n−1)


 Do While statement

A member of the top-checking loops family

Makes VBA execute one or more statements zero or more times, while a condition is true.
Function DoWhileDemo(N)
If N < 2 Then
DoWhileDemo = 1
Else
i = 1
j = 1
Do While i <= N
j = j * i
i = i + 1
Loop
DoWhileDemo = j
End If
End Function
 Do…Loop While statement

A member of the bottom-checking loops family.

Makes VBA execute one or more statements one or more times, while a condition is true
Function DoLoopWhileDemo(N)
If N < 2 Then
DoLoopWhileDemo = 1
Else
i = 1
j = 1
Do
j = j * i
i = i + 1
Loop While i <= N
DoLoopWhileDemo = j
End If
End Function
 Do Until Statement

A member of the top-checking loops family.

Makes VBA execute one or more statements zero or more times, until a condition is met.
 Do…Loop Until Statement

a member of the bottom-checking loops family.

makes VBA execute one or more statements one or more times, until a condition becomes true.

 For Loop

Used mainly for loops where the number of times the action is repeated is known in advance.
Function ForDemo1(N)
If N <= 1 Then
ForDemo1 = 1
Else
j = 1
For i = 1 To N Step 1
j = j * i
Next i
ForDemo1 = j
End If
End Function
Do While: kiểm tra điều kiện trước khi lặp, lặp lại vòng lặp cho đến khi điều kiện sai (chỉ dừng khi điều
kiện từ đúng thành sai)

Do Until: kiểm tra điều kiện trước khi lặp; lặp lại vòng lặp cho đến khi điều kiện được thỏa mãn (ngược
lại với vòng lặp While)
Do Loop While: thực hiện lặp trước khi kiểm tra điều kiện vì thế Do Loop While sẽ thực hiện lệnh ít nhất
1 lần ngay cả khi điều kiện sai

Do Loop Until: thực hiện lặp trước khi kiểm tra điều kiện vì thế Do Loop While sẽ thực hiện lệnh ít nhất 1
lần ngay cả khi điều kiện được thỏa mãn

For Loop: tương tự như vòng lặp Do While (kiểm tra điều kiện trước khi lặp), được dùng trong trường
hợp biết trước số lần lặp

9. Using Excel Functions in VBA


Consider the following statistical experiment. You flip a coin 2 times and count the number of times the
coin lands on heads. This is a binomial experiment because:

 The experiment consists of repeated trials. We flip a coin 2 times.


 Each trial can result in just two possible outcomes - heads or tails.
 The probability of success is constant - 0.5 on every trial.
 The trials are independent; that is, getting heads on one trial does not affect whether we get heads
on other trials.

The probability distribution of binomial random variable is

( p , n , x ) C x p x (1− p)n−x
n
¿
p: probability of success
x : number of successes
n : number of trials
n!
C xn= : The number of combinations of n things, taken x at a time.
( n−x ) ! x !
The excel function Combin(n,x) does this above calculation
Function Binomial(p, n, x)
Binomial = Application.WorksheetFunction.Combin(n, x) * p ^ x * (1 -
p) ^ (n - x)
End Function
10. Using User-Defined Functions in User-Defined Functions
Exercise 4+5

A bank offers different yearly interest rates to its customers based on the size of the deposit in the
following way:
 For deposits up to 1,000, the interest rate is 5.5%
 For deposits from 1,000 and up to 10,000, the interest rate is 6.3%
 For deposits from 10,000 and up to 100,000, the interest rate is 7.3%
 For all other deposits the interest rate is 7.8%

Calculate the future value of a deposit with the bank assuming the deposit and accrued interest is
reinvested for a given number of years.

Step 1: Implement the function Interest(Deposit) in VBA.


Function Interest(Deposit)
If Deposit < 0 Then
Interest = " #VALUE! "
ElseIf Deposit <= 1000 Then
Interest = 5.5 / 100
ElseIf Deposit <= 10000 Then
Interest = 6.3 / 100
ElseIf Deposit <= 100000 Then
Interest = 7.3 / 100
Else
Interest = 7.8 / 100
End If
End Function
Step 2: Implement a function NewDFV(Deposit, Years) Lãi nhập vào vốn gốc
Function NewDFV(Deposit, Years)
NewDFV = Deposit * (1 + Interest(Deposit)) ^ (Years)
End Function

Result
GETFORMULA to show the function you used page 1
Function getformula(r As Range) As String
Application.Volatile
If r.HasArray Then
getformula = "<–– " & " {" & r.FormulaArray & "}"
Else
getformula = "<–– " & " " & r.FormulaArray
End If
End Function

You might also like