Professional Documents
Culture Documents
1. Overview
Visual Basic for Applications (VBA) provides a complete programming language and environment fully
integrated with Excel and all other Microsoft Office applications.
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
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.
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
Open a new module, select Insert – Module from the menu in the VBA editor environment
1. A header line with the name of the function and a list of parameters.
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
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.
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
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.
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
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.
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:
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)
If P1=-22 (<-10)
P2=6 (>5) then nestedif=3
P2=4 (<5) then nestedif=4
If P1=6 (<10)
If P1=-5 (<10)
P2=7 (>5) And P1 different from P2 (-5 different from 7) then nestedif=6
If P1=4 (<10)
Usually Boolean expressions are constructed using the Comparison and/or Boolean operators.
The next function uses a Boolean operator to check whether two conditions hold at the same time.
Only if both conditions are violated, ordemo returns 12. Otherwise, it returns 3.
8. Loops
Are used when you need to do something repeatedly.
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
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
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
Makes VBA execute one or more statements zero or more times, until a condition is met.
Do…Loop Until Statement
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
( 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.
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