0% found this document useful (0 votes)
68 views

CTA - 04 VBA Basics.18 PDF

Declarative statements Dim maxAVSA As Double Dim wr As Double Assignment statement maxAVSA = 28200 wr = 1 IF structure If val_year < 2020 Then coord_deduction = 7/8 * maxAVSA Else coord_deduction = 0.75 * maxAVSA End If Function eval_LPP_salary(val_year As Integer, _ gross_sal As Double) As Double HEC Lausanne Computanional Tools for Actuaries (CTA) CTA - G. Zucchinetti 21 Function definition - Function name:

Uploaded by

david Abotsitse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

CTA - 04 VBA Basics.18 PDF

Declarative statements Dim maxAVSA As Double Dim wr As Double Assignment statement maxAVSA = 28200 wr = 1 IF structure If val_year < 2020 Then coord_deduction = 7/8 * maxAVSA Else coord_deduction = 0.75 * maxAVSA End If Function eval_LPP_salary(val_year As Integer, _ gross_sal As Double) As Double HEC Lausanne Computanional Tools for Actuaries (CTA) CTA - G. Zucchinetti 21 Function definition - Function name:

Uploaded by

david Abotsitse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Visual Basic’s Basics

Excel

Giovanni Zucchinetti
[email protected]

Adapted from the course « Notions informatiques – Modèles de calcul »


with kind permission from Prof. Yves Pigneur and Dr. Gabor Maksay

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Agenda

1. Visual Basic Editor


2. Function definition
3. Declaration statement
4. IF statement

CTA - G. Zucchinetti 2
Description of a real-life problem
Net salary of several employees for several periods
Mr Muheim needs a tool in order to compute the net salary of several
employees […]

Additional informations :
- AVS, accident and unemployment contributions correspond to the gross salary
multiplied by the contribution rate
- […]
- The LPP insured salary is coordinated ; the gross salary is first limited to 3 * the
maximum AVS annuity (maxAVSA) (2015 : CHF 3 * 28 200 = 84600) ; then a
coordination amount equal to 7/8 * maxAVSA (i.e. 7/8 * 28200) is subtracted ; in
any case the minimum LPP insured salary is equal to 1/8 * maxAVSA. If the
gross salary is less than 6/8 * the maximum AVS annuity (maxAVSA) then the
LPP insured salary is null
- After 2019, the coordination amount is expected to be equal to 75% of the
maxAVSA.

CTA - G. Zucchinetti 3
Dependency graph - Solution

CTA - G. Zucchinetti 4
Sub-model - Alternative implementation

CTA - G. Zucchinetti 5
Sub-models - Implementation
• With Excel, putting the sub-model in a separate sheet won’t
provide a much better solution than the integration in the main
model :
- if you link the intermediate results cells (or the input data) to the main
model cells, the sub-model doesn’t act as a server for two different
clients : you have to implement the sub-model twice
- the same difficulty arises with dimensioned client models : you have to
replicate n-times the sub-model

• We need a new mechanism : user-programmed functions with


Visual Basic (→ this lesson)

CTA - G. Zucchinetti 6
Development approach
Perceived
reality Description of the problem

Requirements analysis
Design Design of the model
Validation

Abstract
model Description of the problem

Implementation
Translation in a computer language

Visual Solution for the problem ; uses for specific


Basic computations [Hainault 2002]

CTA - G. Zucchinetti 7
Microsoft Visual Basic for
Applications
• Visual Basic for Applications (VBA) is an implementation of
Microsoft's Visual Basic, a programming language and associated
development environment which is built into most Microsoft Office
applications
• It can be used to control almost all aspects of the host application
(i.e. Excel), including manipulating user interface features such as
menus and toolbars and working with custom user forms or dialog
boxes
• VBA is an interpreted language, meaning its instructions are run,
or interpreted, when the source code is run

• Let’s define a function, call it, trace it … and debug it !

CTA - G. Zucchinetti 8
Sub-model - Preparing the translation in
a VB program
Defining a sequence for the algorithm

Input Data
Gross_sal 100'000.00
Val_year 2015
Intermediate Results
Ceiling salary 84'600.00
Limited_salary 84'600.00
Coord_deduction 24'675.00
Coordinated_sal 59'925.00
Min_salary 3'525.00
Coord_min_sal 59'925.00
Lower_limit 21'150.00
Result
LPP_sal 59'925.00

CTA - G. Zucchinetti 9
Sub-model - Preparing the translation in a VB
function
Systematic translation of the Eval_LPP_Salary sub-model
Input Data
Gross_sal 100000 Function’s
arguments
Val_year 2015
work_rate 1
Assignment
Intermediate Results
statement
Ceiling salary =3*maxAVSA
Limited_salary =SI(Gross_sal>Ceiling_salary;Ceiling_salary;Gross_sal)
Coord_deduction =SI(Val_year<2020;7/8*maxAVSA;75%*maxAVSA) IF
statements
Coordinated_sal =Limited_salary-Coord_deduction
Min_salary =maxAVSA/8
Coord_min_sal =SI(Coordinated_sal<Min_salary;Min_salary;Coordinated_sal)
Lower_limit =SI(Val_year<2020;6/8*maxAVSA;75%*maxAVSA*wr)
Result
LPP_sal =SI(Gross_sal<Lower_limit;0;Coord_min_sal) Function’s
result assign.

Declaration
statements
CTA - G. Zucchinetti 10
Sub-models - Solution
• Model Net_Salary
• Input data
- Gross_salary
- …

• Formulas Function
call
- AVS_salaryE,Y = Gross_salaryE,Y fkjhfke
- …
- LPP_salaryE,Y = Eval_LPP_salary(Gross_salaryE,Y;Y;wr)
- …
- AVS_contrE,Y = AVS_salaryE,Y * AVS_contr_rate
- Acc_contrE,Y = Acc_salaryE,Y * Acc_contr_rate
- …
- Net salaryE,Y = Gross_salaryE,Y – Employee_contrE,Y

• Results
- Total AVS contributionY, Total Net SalariesY, …
- …

CTA - G. Zucchinetti 11
Visual Basic Editor

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Visual Basic Editor
• The Visual Basic Editor (VBE) is the environment in which you
work with VBA programming code.
- Tools → Macro → Visual Basic Editor (Outils → Macro → Visual
Basic Editor)
- VBE icon from VBE Toolbar
- ALT + F11

• Three main windows in the VBE


- Project Explorer (projet)
- Properties (propriétés)
- Code

• Other windows in VBE, used for debugging


- Watch (espion)

CTA - G. Zucchinetti 13
Visual Basic Editor

Code
Window
Project
Explorer

Watch
Window

Properties
Window

CTA - G. Zucchinetti 14
Project Explorer
• Lists all projects in any open workbook

• Each workbook has a project, and each


project can have several parts
- Workbook and worksheets
- Modules
- Forms

• Use Insert (Insérer) > Module to add a


new module

CTA - G. Zucchinetti 15
Properties Window
• Contains detailed information about
any selected part of a project in the
Project Explorer.

• Some basic naming and formatting


properties can be modified for
worksheets and workbooks.

• Properties are very important for


user forms
- Formatting
- Position
- Picture
- Scrolling
- Behavior

CTA - G. Zucchinetti 16
Code Window
• Displays the VBA code for the highlighted part of a project in the
Project Explorer.

• When macros are recorded they are simultaneously created as


VBA code in the Visual Basic Editor.

• There are three types of macros or procedures


- Sub procedures
- Function procedures
- Event procedures

CTA - G. Zucchinetti 17
Watch Window
• This window is used for debugging.

• Watch Window displays values of inserted variables.

• Use the View (affichage) menu option to view or hide any window.

CTA - G. Zucchinetti 18
Tracing the code
• “Compile VBA Project” before execution

• Insert Break Points (points d’arrêts - F9)

• Go on step by step (pas à pas détailler - F8)

• Watch the variable values and the statements execution

CTA - G. Zucchinetti 19
- Function
- Declarative statements
- Assignment statement
- IF structure

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Function structure Function’s
arguments

Function eval_LPP_salary(val_year As Integer, _


gross_sal As Double) As Double
Const maxAVSA = 28200#
Dim ceiling_sal As Double Declaration
Dim limited_sal As Double statements

ceiling_sal = 3 * maxAVSA Assignment


statement
If gross_sal > ceiling_sal Then
limited_sal = ceiling_sal
Else IF
limited_sal = gross_sal statement
End If

eval_salaire_LPP = limited_sal Function’s


End Function result assign

CTA - G. Zucchinetti 21
Function declaration
Function eval_LPP_salary(val_year As Integer, _
gross_sal As Double) As Double

End function

• The argument names enclosed in parentheses - val_year and


gross_sal - are placeholders for the values on which the calculation
of the LPP_salary is based.

• The set of instructions is ended by the « end function » key words.

CTA - G. Zucchinetti 22
Declaration statements
- Give name and define variables, constants or
procedures
- Define the type of data the variables will receive

Dim salary as double

memory

salary

CTA - G. Zucchinetti 23
Integers and Doubles
• Both integers and doubles are numerical values.

• Integers are non-decimal numbers ranging in value from -32,768 to


32,767.
- Integers will be used for simple numerical values, counting in
loops, and enumerating arrays.

• Doubles have values from -1.79769E308 to -4.94065E-324 for


negative values and from 4.94065E-324 to 1.79769E308 for
positive values.
- Doubles will be used for any data or calculations.

CTA - G. Zucchinetti 24
String

• A string is a segment of text.

• This text can include upper and lower-case letters,


punctuation marks, and numbers; however these
numbers can not be used in calculations as they will be
viewed as text.
- We will use strings to name objects, label objects,
and label data in spreadsheets.

CTA - G. Zucchinetti 25
Boolean, …
• A Boolean is a variable whose value is either True or False.
- We will use Boolean variables often in logic statements, If, Then
statements, and loops.

• Look at Help for other types like dates, currencies, …


• We’ll come back later on other data types.

CTA - G. Zucchinetti 26
Assignment statement
• The result is stored as the variable salary. A VBA statement that
stores a value in a variable is called an assignment statement,
because it evaluates the expression on the right side of the equal sign
and assigns the result to the variable name on the left.

Dim salary as double


salary = 2 + 3

memory

salary
CTA - G. Zucchinetti 27
VB operators
Operator Mathematical function Example

^ Exponential 2^4=16

* Multiplication 4*3=12

/ Division 12/4=3

Modulus (return the remainder from an


Mod 15 Mod 4=3
integer division)

Integer Division (discards the decimal


\ 19\4=4
places)

+ or & String concatenation "Visual” & "Basic” = "Visual Basic"

CTA - G. Zucchinetti 28
Constants

• A constant variable is a variable whose value will never


change !
- To declare a constant, we use Const
- Const maxAVSA = 28200#

• The const statement is both a declaration and an


assignment statement ! Try to declare maxAVSA without the
# that forces maxAVSA to a double !!!

CTA - G. Zucchinetti 29
“If, Then” Statements
If gross_sal > ceiling_sal Then
limited_sal = ceiling_sal
Else
limited_sal = gross_sal
End If

•“If, Then” statements allow you to perform the same conditional actions that we learned
with the IF function in Excel.

•If a condition is met, a certain set of actions is performed, if it is not, another set of
actions may be performed instead.

•The general format for the “If, Then” statement is : If condition Then
action
End If

CTA - G. Zucchinetti 30
“If, Then” Statements
• The If, Then statement defines the action to performed if the
condition is false by using the Else and ElseIf statements.

• The Else statement allows you to specify the action to be


performed if the condition is not met.

• The ElseIf statement allows you to construct nested If statements.


- That is, instead of performing a direct action if the original
condition is not met, another If condition is considered.

CTA - G. Zucchinetti 31
“If, Then” - Example

If x < 1000 Then


MsgBox “Your number is smaller than 1000.”

ElseIf x < 2000 Then


MsgBox “Your number is greater than 1000 but
less than 2000.”

Else
MsgBox “Your number is larger than 2000”

End If

CTA - G. Zucchinetti 32
Logical Checks and Booleans

• “If, Then” statements are also used with logical checks


and boolean variables.

• Logical checks include And and Or statements similar


to the AND and OR functions we learned in Excel.

CTA - G. Zucchinetti 33
And Logical Check
• The And logical statement requires every condition in the “If, Then”
statement to be true in order for the following action to be
performed.

• If only one of the conditions is false, the action will not be


performed and the following Else or ElseIf statement will be read or
the “If, Then” statement will end.

• This statement structure is as follows


If condition1 And condition2 And condition3 And … Then
action 1
Else (or ElseIf)
action 2
End If

CTA - G. Zucchinetti 34
Or Logical Check
• The Or logical statement requires every condition in the “If, Then”
statement to be true in order for the following action to be
performed.

• Every condition would have to be false to skip the following action


and read the Else, ElseIf, or End If statements.

• This statement structure is as follows


If condition1 Or condition2 Or condition3 And … Then
action 1
Else (or ElseIf)
action 2
End If

CTA - G. Zucchinetti 35
And, Or - Example
If x < 1000 And x > 500 Then
MsgBox “Your number is between 500 and 1000.”
Else
MsgBox “Your number is smaller than 500 or greater than 1000.”
End If

• Here, the And check requires that both conditions be met.

• If this is true, then the value of x should be between 500 and 1000,
thus the first Message Box is displayed.

• However, if either condition is false, then the statement in the second


Message Box must be true.

CTA - G. Zucchinetti 36
And, Or - Example (continuation)
If x < 1000 And x > 500 Then
MsgBox “Your number is smaller than 500 or greater than 1000.”
Else
MsgBox “Your number is between 500 and 1000.”
End If

• Here we can see the difference in using the Or Logical Check.

• With Or, either of the conditions can be true to display the first
Message Box.
- That is either x can be greater than 1000 or less than 500.

• If neither condition is met, then the second Message Box must be


true.

CTA - G. Zucchinetti 37
Using Boolean Variables
• If, Then statements are used with Boolean variables to check if
their values are True or False.

• You can simply use the following two statements

If variable = True Then


action 1
End If
------------------------------
If variable = False Then
action 2
End If

CTA - G. Zucchinetti 38
Using Boolean Variables

• To check if a Boolean variable is True, you can also just


state the name of the variable.
- that is, the default value of any Boolean variable is True.

• Instead of the first statement in the previous slide, you can


just type
If variable Then
action
End If

CTA - G. Zucchinetti 39
Boolean - Example

If found Then
MsgBox “The solution has been found.”
ElseIf found = False Then
MsgBox “The solution has not been
found.”
End If

CTA - G. Zucchinetti 40
Returning results
Function eval_LPP_salary(val_year As Integer, _
gross_sal As Double) As
Double
Const maxAVSA = 28200#
Dim ceiling_sal As Double
Dim limited_sal As Double

ceiling_sal = 3 * maxAVSA

eval_salaire_LPP = limited_sal
End Function

• Because the variable eval_salaire_LPP has the same name as the function
procedure, the value stored in the variable is returned to the worksheet formula that
called the eval_salaire_LPP function.
• Generally, it’s the last statement of the function !

CTA - G. Zucchinetti 41
Forces variable declaration

If not defined, the default type is variant


(try to avoid it)

Bloc of statements

CTA - G. Zucchinetti 42
Documenting with comments

Use the REM keyword or « ’ »

CTA - G. Zucchinetti 43
Calling the user-defined function

CTA - G. Zucchinetti 44
References
• [Maksay 08] Maksay Gabor, Pigneur Yves, Modéliser par l'exemple, Presses
polytechniques et universitaires romande, 2008,
http://www.ppur.org/produit/290/9782880748951/Modeliser%20par%20lexempl
e%20

• [Seref 07] Michelle M.H. Şeref, Ravindra K. Ahuja, and Wayne L. Winston ;
Developing Spreadsheet-Based Decision Support Systems Using Excel and
VBA for Excel ; Dynamic Ideas, Belmont, Massachusetts 2007

• [Hainault 02], Jean-Luc Hainault, Bases de données et modèles de calcul


(3ème édition), Dunod, 2002

CTA - G. Zucchinetti 45

You might also like