Control Structures VBA: HEC Lausanne Computanional Tools For Actuaries (CTA)
Control Structures VBA: HEC Lausanne Computanional Tools For Actuaries (CTA)
VBA
Giovanni Zucchinetti
[email protected]
HEC Lausanne
Computanional Tools for Actuaries (CTA)
Agenda
1. Sub procedures
2. Input and Message boxes
3. Loops
4. Case statements
2
Sub procedures
HEC Lausanne
Computanional Tools for Actuaries (CTA)
Sub Procedures
• Functions are named blocks program code that perform a specific task
and return a result. The task can be as simple as calculating the sum of
two numbers. A procedure is simply a function that does not return a
result, procedures are used for their side effects.
• You should group various actions into several smaller sub procedures
rather than having one large sub procedure in which the entire program is
written.
• The ideal module structure for your program is to have one Main() sub
procedure from which other sub procedures are called.
- This Main macro will usually be assigned to a “Start” button on the “Welcome”
sheet.
• To call another sub procedure, we use the command Call followed by the
sub procedure name.
CTA - G. Zucchinetti 4
Example
• For example, consider three different sub procedures, called
GetInput(), Calculations(), and CreateReport().
• We can then call these three sub procedures from the Main() sub
procedure as follows.
Sub Main()
Call GetInput
Call Calculations
Call CreateReport
End Sub
• You can also call other sub procedures from these three sub
procedures.
CTA - G. Zucchinetti 5
Public and Private Sub Procedures
• A sub procedure can be defined as Public or Private.
CTA - G. Zucchinetti 6
Example
• Consider four small sub procedures.
• Two of these procedures are private: Test1() and Test2()
- Since they are in the same module, they can call one another.
CTA - G. Zucchinetti 7
Example (continuation)
• The third sub procedure called Test3() is public but in another
module.
• We are not allowed to call either of the private sub procedures in
the original module.
- That is, Test3() cannot contain the code: Call Test1 or Call Test2.
• However, we can call this public procedure from one of our private
procedures.
Private Sub Test1()
MsgBox "This is Test1"
Call Test3
End Sub
CTA - G. Zucchinetti 8
Example (continuation)
• The fourth sub procedure called Test4() is also public and in the
same module as Test1() and Test2().
• Even though Test4() is public it can still call the private procedures
since they are in the same module.
Sub Test4()
MsgBox “ This is Test4”
Call Test1
End Sub
CTA - G. Zucchinetti 9
Input and messages
boxes
HEC Lausanne
Computanional Tools for Actuaries (CTA)
Message Box and Input Box
• Message Boxes allow you to print something for the user to
see in a small dialog box.
CTA - G. Zucchinetti 11
Message Box
• You can also use the MsgBox function to specify button types and
response types
- MsgBox (prompt, [buttons], [title], [helpfile, context])
CTA - G. Zucchinetti 12
MsgBox Function
• The prompt is either the text or variable (or concatenation of both)
which will be displayed in the dialog box.
• The buttons argument takes a VB Constant value to determine
the number and style of buttons available to the user.
- vbOKOnlyDisplays an OK button only
- vbOKCancelDisplays OK and Cancel buttons
- vbYesNoCancelDisplays Yes, No, and Cancel buttons
- vbYesNoDisplays Yes and No buttons
• The title argument allows you to enter text a title for the dialog
box.
• The helpfile and context arguments allow you to give the user
help options.
CTA - G. Zucchinetti 13
MsgBox Function (cont’d)
You can also capture the user’s response to your Message Box
with a VBA variable called response.
- vbOKIf response was OK
- vbCancelIf response was Cancel
- vbAbortIf response was Abort
- vbRetryIf response was Retry
- vbIgnoreIf response was Ignore
- vbYesIf response was Yes
- vbNoIf response was No
CTA - G. Zucchinetti 14
InputBox Function
• The InputBox function is always assigned to a variable.
• This function takes the following general form:
- InputBox (prompt, [title], [default], [xpos], [ypos], [helpfile, context])
• The prompt and title arguments of the InputBox function are the
same as those of the MsgBox function.
• The default argument allows you enter a default value to display in
the Input Box.
• The xpos and ypos arguments allow you to position the Input Box
relative the left and top edges of the screen.
• The helpfile and context arguments are the same as those of the
MsgBox function.
CTA - G. Zucchinetti 15
Loops
HEC Lausanne
Computanional Tools for Actuaries (CTA)
Loops
• Loops are programming structures which allow you to repeat a set
of actions a certain number of times.
CTA - G. Zucchinetti 17
Specification of a loop - Example :
Integer Division
modulo
• Being given :
- two strictly positive whole numbers called dividend and divider,
CTA - G. Zucchinetti 18
Division (algorithm)
first
intuition
read Dividend
read Divider
show Quotient
show Remainder
CTA - G. Zucchinetti 19
Solution idea
Dividend = 22
Divider = 4
22 - 4 = 18
18 - 4 = 14
14 - 4 = 10 Quotient = 5 (subtractions)
10 - 4 = 6
6 - 4 = 2
Remainder = 2 (difference)
CTA - G. Zucchinetti 20
Iteration
1. <body of the loop>
2. <continuation condition>
3. <initialization>
CTA - G. Zucchinetti 21
Construction of the iteration - Start
22 - 4 = 18
18 - 4 = 14 Differences already computed
14 - 4 = 10 Differences to be computed
10 - 4 = 6
...
Known difference
CTA - G. Zucchinetti 22
Iteration - Body of the loop
CTA - G. Zucchinetti 23
Iteration - Situation after one step
22 - 4 = 18
18 - 4 = 14
14 - 4 = 10 Differences already computed
10 - 4 = 6 Differences to be computed
...
Known difference
CTA - G. Zucchinetti 24
Iteration’s structure - Initialization
22 - 4 = 18 Differences to be computed
18 - 4 = 14
Known difference
...
CTA - G. Zucchinetti 25
Iteration - Initialization and condition
• Initialization
In order to be in proper situation for the first execution
difference dividend
nsubtr 0
• Continuation condition
Repeat the instructions ...
while difference >= divider
CTA - G. Zucchinetti 26
Iteration
1. <body of the loop>
difference difference - divider
nsubtr nsubtr + 1
2. <continuation condition>
while difference >= divider
3. <initialization>
difference dividend
nsubtr 0
CTA - G. Zucchinetti 27
Integer Division (algorithm)
read Dividend Loop
read Divider
Difference dividend
nsubtr 0
CTA - G. Zucchinetti 28
Do Loops
• There are two main Do Loops
- Do, While
- Do, Until
CTA - G. Zucchinetti 29
Do Loop Structures
In the structure below, a while condition is considered before a set of
actions will be performed.
Do While count < 10
actions
count = count + 1
Loop
In the second structure, the set of actions will be performed and then
the while condition will be checked before the actions are repeated.
Do
actions
count = count + 1
Loop While count < 10
CTA - G. Zucchinetti 30
While vs Until
The difference between looping while the condition is met and
until the condition is met is important to note.
- For the Do, While loop, if the condition is true this signals the
loop to repeat the actions.
- However, for the Do, Until loop, if the condition is true, this
signals the loop to stop repeating the actions.
CTA - G. Zucchinetti 31
While vs Until
Compare the values generated by the following two loops.
Do While count <= 10
x = 2*x
count = count + 1
Loop
For this first loop, assuming the value of the count variable is initialized to be 1,
the condition will be met the first time (1 <= 10) and the next 10 times.
CTA - G. Zucchinetti 32
While vs Until
Do Until count = 10
x = 2*x
count = count + 1
Loop
This second loop, however, will stop repeating when count reaches 10
(but not including 10)
CTA - G. Zucchinetti 33
Boolean Variables in Do Loops
CTA - G. Zucchinetti 34
Boolean Variables
Do While found = False
actions
If x > 100 Then
found = True
End If
Loop
Here we are performing some actions while a certain result is still not
found.
Once the found variable is set to True, the While condition is no longer
met and the loop ends.
CTA - G. Zucchinetti 35
For Loops
The For, Next and For Each, Next loops are used to repeat a
loop while counting up toward to down to a certain number.
We refer to them both generally as For Loops.
CTA - G. Zucchinetti 36
For, Next
The more common of these two structures is the For, Next loop.
CTA - G. Zucchinetti 37
Integer Division - VBA program
CTA - G. Zucchinetti 38
For, Next - Example
Function factorielle(n As Integer) As Double
Dim i As Integer
Dim cumul As Double
cumul = 1
For i = 1 To n
cumul = cumul * i
Next i
factorielle = cumul
End Function
CTA - G. Zucchinetti 39
For, Next
CTA - G. Zucchinetti 40
For, Next
If you want to count up towards a number, the Step value should
be positive and the start value should be less than the end value.
For i = 1 to 10 Step 2
actions
Next I
CTA - G. Zucchinetti 41
For Each, Next
The For Each, Next loop works almost identically to the For,
Next loop.
CTA - G. Zucchinetti 42
For Each, Next
CTA - G. Zucchinetti 43
Exit Statements
As you develop and run longer programming structures such as nested
If, Then statements and Do Loops, you may want a way to exit the
current set of actions at any time.
VBA provides several Exit Statements which allow current actions to
stop and moves the program to following code.
- Exit For will stop executing a For, Next or For Each, Next loop and
move to the next line of code after the Next statement.
- The Exit Do code will stop executing a Do Loop and move to the next
line of code after the Loop statement.
I suggest to avoid using those Exit statements and rather structure
your function or loop so that the exit condition is an end of loop
condition !
CTA - G. Zucchinetti 44
Select, Case
HEC Lausanne
Computanional Tools for Actuaries (CTA)
Select, Case
The Select, Case statement is used to list possible situations in which
certain actions should be performed.
CTA - G. Zucchinetti 46
Select, Case
We can also give a range of values as a case instance.
CTA - G. Zucchinetti 47
Select, Case
There is also an optional Case Else statement which can be used to
specify all other cases which are not listed.
CTA - G. Zucchinetti 48
Select, Case
You may also include some conditions as cases instead of simple
instances.
CTA - G. Zucchinetti 49
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
%20lexemple%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
CTA - G. Zucchinetti 50