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

Control Structures VBA: HEC Lausanne Computanional Tools For Actuaries (CTA)

The document discusses different control structures in VBA including sub procedures, input and message boxes, loops, and case statements. It provides examples of how to create and call sub procedures, use message boxes and input boxes to prompt users, and implement different types of loops to repeat actions a specified number of times. The examples demonstrate how to divide two numbers using loops to iteratively subtract the divider from the dividend until the remainder is calculated.

Uploaded by

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

Control Structures VBA: HEC Lausanne Computanional Tools For Actuaries (CTA)

The document discusses different control structures in VBA including sub procedures, input and message boxes, loops, and case statements. It provides examples of how to create and call sub procedures, use message boxes and input boxes to prompt users, and implement different types of loops to repeat actions a specified number of times. The examples demonstrate how to divide two numbers using loops to iteratively subtract the divider from the dividend until the remainder is calculated.

Uploaded by

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

Control structures

VBA

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. 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.

• A private sub procedure is declared by putting the word Private


before the Sub statement.
- Private sub procedures can only be called from procedures in the same
module.
- Private sub procedures are also not listed when you try to run a macro
in Excel.

• A public sub procedure can be called from any other procedure.


- The word Public can be put in front of the Sub statement, or the Sub
statement can be written without a preceding statement.

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.

Private Sub Test1()


MsgBox "This is Test1"
Call Test2
End Sub
-------------------------------
Private Sub Test2()
MsgBox "This is Test2"
End Sub

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.

• Input Boxes allow you to prompt the user to enter some


value in a small dialog box.

CTA - G. Zucchinetti 11
Message Box

• You can print the following with a Message Box


- Text
- Variable values
- Both using concatenation with & sign

• 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.

• The number of loops can be specified by counting up to (or down


to) a certain value.
- For, Next
- For Each, Next

• Or the loops can run continuously while or until a certain condition


is met.
- Do, While
- Do, Until

CTA - G. Zucchinetti 17
Specification of a loop - Example :
Integer Division
modulo

• Being given :
- two strictly positive whole numbers called dividend and divider,

• The goal is to build a program which :


- calculates and communicates to the user the quotient and the
remainder of the whole division of these two numbers

CTA - G. Zucchinetti 18
Division (algorithm)
first
intuition
read Dividend
read Divider

<compute the quotient and the remainder >

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

What is known (in order to progress)


difference = 14
divider = 4
nsubtr = 2

CTA - G. Zucchinetti 22
Iteration - Body of the loop

difference difference - divider


nsubtr nsubtr + 1

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

What is known (in order to progress)


difference = 10
divider = 4
nsubtr = 3

CTA - G. Zucchinetti 24
Iteration’s structure - Initialization

Differences already computed

22 - 4 = 18 Differences to be computed
18 - 4 = 14
Known difference
...

What is known (in order to progress)


difference = 22
divider = 4
nsubtr = 0

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

While difference >= divider


difference difference - divider
nsubtr nsubtr + 1

Write(“quotient =”) & nsubtr


Write(“remainder =”) & difference

CTA - G. Zucchinetti 28
Do Loops
• There are two main Do Loops
- Do, While
- Do, Until

• These Do Loops perform a set of actions repeatedly while or until


a condition is met.

• There are two main structures for these loops


- Specify While or Until condition before actions
- Specify While or Until condition after actions

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.

The action (x = 2*x, again assuming x is initially 1) will therefore be


repeated 10 times yielding the final values of :
- x = 2^10
- count = 11

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)

Thus yielding final values of : - x = 2^9


- count = 10

CTA - G. Zucchinetti 33
Boolean Variables in Do Loops

Do Loops can also be used with Boolean variables.


- That is, the Boolean variable can be used as the condition for
the Do, While or Do, Until loops.

These conditions usually imply some nested If, Then statements


which would change the value of the Boolean variable once a
certain result is found.

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.

We perform the counting using some simple index variable such


as i or a counting variable such as count or iteration.
These variables are integer data types.

CTA - G. Zucchinetti 36
For, Next

The more common of these two structures is the For, Next loop.

The structure of this loop is as follows

For counter = start To end


actions
Next counter

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

There is also a Step parameter used with this loop.

The Step value specifies how much the counter


variable should increase or decrease during each
loop.

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

If you wish to count down to a number, the Step value should be


negative and the start value should be greater than the end
value.
For i = 10 to 1 Step -1
actions
Next i

CTA - G. Zucchinetti 41
For Each, Next
The For Each, Next loop works almost identically to the For,
Next loop.

The only difference is that For Each, Next is counting a certain


number of objects in a group of objects.
- That is objects are counted rather than using a counter variable.

CTA - G. Zucchinetti 42
For Each, Next

For example, if we want to count the number of worksheets


in the current workbook, we could declare a worksheet
variable ws and use the following For Each, Next loop with
some count variable.

For Each ws In ActiveWorkbook.Worksheets


count = count + 1
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.

The general structure of the Select, Case statement gives a particular


expression which is to be evaluated and a list of cases of possible
values of that expression.

Select Case number


Case 1
MsgBox “ Your number is 1.”
Case 2
MsgBox “ Your number is 2.”
End Select

CTA - G. Zucchinetti 46
Select, Case
We can also give a range of values as a case instance.

Select Case number


Case 1 To 5
MsgBox “ Your number is in the interval (1, 5).”
Case 6 To 10
MsgBox “ Your number is in the interval (6, 10).”
End Select

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.

The ability to give a range of values as a case instance using the To


statement can be extended to string values.

Select Case name


Case “ Adams” To “ Henderson”
MsgBox “ Please look in files A to H.”
Case “ Ignatius” To “ Nichols”
MsgBox “ Please look in files I to N.”
Case Else
MsgBox “ Please look in files N to Z.”
End Select

CTA - G. Zucchinetti 48
Select, Case
You may also include some conditions as cases instead of simple
instances.

This is useful in replacing several ElseIf statements in an If, Then


structure.

Select Case number


Case number < 10
MsgBox “ Your number is less than 10.”
Case number > 10
MsgBox “ Your number is greater than 10.”
End Select

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

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


édition), Dunod, 2002

CTA - G. Zucchinetti 50

You might also like