CTA - 07 Scope Types Functions.16

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

VBA

Scope, variables,
XL interaction
Giovanni Zucchinetti
giovanni.zucchinetti@gitec.ch

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)
1
Agenda

1. Variable scope
2. More on Data types
3. By val and by ref
4. More on VBA functions
5. Referencing Excel’s ranges
6. Using XL functions from VBA

2
Variable Scope

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Variable Scope
Every variable has a scope associated with it. This scope refers to the
area of code where the variables will be recognized.

Variables (and constants) have a defined scope within the program.


The scope for a variable can either be:
- Procedure Level - Also known as a local variable.
- Module Level Private - A private module level variable is visible to only
the module it is declared in.
- Module Level Public - A public module level variable is visible to all
modules in the project.
It is important to understand the scope of each variable you declare.

You must check your code to see if a variable will be used in only one
sub procedure, or function procedure, or if it will be used in several
different procedures.

CTA - G. Zucchinetti 4
Procedure level variables
A local or procedure level variable is declared inside an
individual procedure or function and is not visible outside that
subroutine

Local variables can only be used in the procedure in which they


are declared in.

When the procedure or function ends the variable is


automatically removed and the memory is released.

One of the great advantages of local variables is that we can use


the same name in different subroutines without any conflicts.

CTA - G. Zucchinetti 5
Some examples
Example 1 Example 2
Sub Sub1() Function Func1(age as
Dim i As Integer integer) as integer
i = 3 Func1 = age * 2
End Sub End Function
-------------------- ---------------------
Sub Sub2() Sub Sub2(age as integer)
Dim i As Integer Dim x as integer
i = 2 x = age + 2
call Sub1() MsgBox Func1(x)
MsgBox i End Sub
End Sub

CTA - G. Zucchinetti 6
Some examples
Example 3
Function Func1(age as
integer) as integer
Dim age as integer
Func1 = age * 2
End Function
---------------------
Sub Sub2(age as integer)
Dim x as integer
x = age + 2
MsgBox Func1(x)
End Sub

CTA - G. Zucchinetti 7
Private Variables
A Private variable is declared using the Dim statement.

This variable can be private on two levels


- Procedure level = only used in the particular sub procedure in
which it was declared.
- Module level = used in any procedure in the module, but only in
the particular module in which it was declared.

CTA - G. Zucchinetti 8
Procedure Level vs Module Level
Procedure level private Module level private
declaration declaration

Sub Sub1() Option Explicit


Dim i As Integer Dim i As Integer
.... -------------------
End Sub Sub Sub1()
-------------------- Dim i as Integer
Sub Sub2() i = 3
Dim i As Integer End Sub
... -------------------
End Sub Sub Sub2()
i = 4
End Sub

CTA - G. Zucchinetti 9
Module Public Variables
- A Module Public variable on the other hand can be used in any sub
procedure in any module.
- To declare a public variable or constant, we use the Public statement.
- Public gValuationYear As Integer
- Public Const kMaxAge As Integer = 100

- A public module level variable is visible to all modules in the project.


- These are also know as project level or global variables
- You must insert these statements at the very top of your modules, before
any procedures or functions.
- Project scope variables must also be declared in a standard code
module and not is a userform. Declaring a variable as Public inside a
userform does not make it public. It is still private and only visible to that
userform code module only.

CTA - G. Zucchinetti 10
Understanding the Lifetime of Variables
The difference between lifetime and scope is quite simple.
- Lifetime - Refers to how long or when the variable is valid (i.e. how long will
it retain its value for).
- Scope - Refers to where the variable can be accessed.
In the example below :
- The lifetime of the local variable "imylocal" extends from the moment
ProcedureOne is entered to the moment ProcedureOne has finished.
- However the local variable "imylocal" still exists when ProcedureTwo is
called, it is just out of scope.

CTA - G. Zucchinetti 11
More on data types

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Declaring multiple variables
VBA does not let you declare a group of variables to all be of the same
datatype. You must specify the type of each variable explicitly.

This statement is valid although the variable sFirstName is defined as a


Variant variable and not as a string variable:
- Dim sFirstName, sLastName As String

You should always try and declare each variable on a separate line
- Dim sFirstName As String
- Dim sLastName As String

You could put this on one line :


- Dim sFirstName As String, sLastName As String

CTA - G. Zucchinetti 13
Converting types
Variables of one type can be converted into another type. This is often
called Casting.
Casting can either be narrowing or widening
- Widening Cast - This is one in which the conversion is to a datatype
that can accommodate every possible value in the existing datatype.
For example a Long can accommodate every possible value held by an
Integer. Casting from an Integer to a Long is a widening conversion.
- Narrowing Cast - This is one in which the conversion is to a datatype
that does not accommodate every possible value in the existing
datatype. For example an Integer cannot be accommodate every
possible value held by an Long. Casting from a Long to an Integer is a
narrowing conversion. Information may be lost
There are two mechanisms that can be used to accomplish this
conversion:
- Implicit conversion - Is invoked automatically when a value of one data
type is assigned to a value of another. Widening casts are often implicit.
- Explicit conversion - Is by using one of the following conversion
functions
CTA - G. Zucchinetti 14
Testing the type of a variable
The type of variable, or the compatibility of its content with a
type, can be check by a function, for instance:
- IsDate Function
- IsNumeric Function

Example : IsDate (expression)


- IsDate returns True if the expression is a date or can be
converted to a valid date; otherwise, it returns False.
- The required expression argument is a Variant containing a date
expression or string expression recognizable as a date or time.

CTA - G. Zucchinetti 15
Type conversion Functions
There are several functions in VBA that can be used to convert
one data type to another.

Two main conversion functions used with numerical values are


CInt and CDbl.
- CInt converts a variable to an Integer data type :
CInt(variable or expression)
- CDbl converts a variable to a Double data type :
CDbl(variable or expression)

The Val function also extracts a numerical value from a string.


The input for this function is an expression.
- Val(expression)

CTA - G. Zucchinetti 16
Conversion Functions (cont’d)
Any numeric expression can also be converted to a string using the
CStr function. The input for this function is again any variable or
expression :
- CStr (variable or expression)

The CDate function converts values into the Date data type. This data
type is necessary to work with dates in your code for comparisons or
calculations.
- Cdate (variable or expression)

Two other useful conversion functions are Asc and Chr. These
functions, which use the ASCII list of numbers and characters, can be
used to convert letters to numbers and numbers to letters, respectively :
- Asc(character): Asc(“A”) = 65
- Chr(number): Chr(65) = “A”

CTA - G. Zucchinetti 17
User-defined types
You define user defined datatypes outside at the very top of your
modules before any procedures or functions.
It is important to visually distinguish user defined types from other
datatypes. For this reason is should always be prefixed with an
uppercase T.
Example : Public Type TActive
fID As Long
fName As String
fSalary As Double
End Type

Dim myActive As Tactive


MyActive.fID = 3
With MyActive
.Name = “Joe”
.fSalary = 100000
End With

CTA - G. Zucchinetti 18
Passing arguments to
functions or procedures

HEC Lausanne
Computanional Tools for Actuaries (CTA)
ByRef and ByVal
• When getting the value of a variable from a procedure or function
parameter you have two ways to request it. Either you can request for
it to be passed ByRef (default) or ByVal.
- Passing ByVal
Private Sub TestSub (ByVal strPath As String)
- Passing ByRef
Private Sub TestSub (ByRef strPath As String) or just
Private Sub TestSub (strPath As String)
• When you pass ByVal, Visual Basic passes a copy of the variable to
the procedure. This way the procedure gets the value, but any
changes it makes will not affect the original variable.
• When you pass ByRef, Visual Basic passes a pointer to the
procedure. This is a reference so that the procedure knows where to
find the variable in the memory. Any changes the procedure makes to
this variable will effect the original one, as they are the same thing,
however the variable does not need to be declared as public if you
were wanting the procedure to access the variable any other way.

CTA - G. Zucchinetti 20
Risk of side effects

Example

CTA - G. Zucchinetti 21
Optional arguments
Arguments to a procedure or function can be specified as optional.
- You can specify as many optional arguments as you like although they
must come at the end of the parameter list.
- When a parameter has been declared with the Optional keyword you
can call the procedure (or function) with or without an argument for this
parameter.
- If we omit an optional argument in the middle of a list, we must include
an empty space when calling that procedure.
- When you declare a parameter as being optional you can define its
default value.
- The IsMissing function determines whether an optional argument has
been passed to the procedure.
Examples :
- Sub Procedure_One (ByVal vText as String, Optional ByVal
sFontName As String = "Arial", Optional ByVal vFontSize As Double)
- … If IsMissing(vFontSize) Then …

CTA - G. Zucchinetti 22
Positional and named arguments
Some procedures, especially some of the built-in methods, can often
contain a large number of parameters where in fact all these
parameters are declared as optional.
If you have a lot of optional arguments the procedure call can get very
messing.
Positional arguments passing :
- Call Procedure_One (“Hello”, , 42)
- The normal way to call a procedure and pass arguments is to pass in
the arguments you want and leave the rest blank. It is the position of
the argument that tells it what parameter it is.
Named arguments passing:
- Procedure_One vFontSize := 42 , vText := “Hello”
- If you use named arguments, you don't have to include commas to
denote missing positional arguments. Using named arguments makes it
easier to keep track of which arguments you passed and which you
omitted. You can even change the order of the arguments.

CTA - G. Zucchinetti 23
VBA functions
Calling Excel’s functions
from VBA

HEC Lausanne
Computanional Tools for Actuaries (CTA)
VBA Math Functions

We can use typical math functions in VBA without needing


to create a formula in the spreadsheet.

There are : - Typical Math Functions


- Trigonometric Functions
- Derived Math Functions

CTA - G. Zucchinetti 25
Typical Math Functions

We will describe six basic math functions :


- Abs
- Sqr
- Int
- Rnd
- Exp
- Log

CTA - G. Zucchinetti 26
Abs Function
The Abs function calculates the absolute value of a variable.

This function can be used with both integer and double data
types (as well as with other numerical variables).

It will return the same data type which is used in the function.
- Abs(-10) = 10

CTA - G. Zucchinetti 27
Sqr Function
The Sqr function calculates the square root of a number.

It can also be used with any numerical data type (must be


greater than 0).

It will always return a double data type.


- Sqr(100) = 10

CTA - G. Zucchinetti 28
Int Function
The Int function removes the decimal part of a double variable
and returns the integer part.

The result will be an integer data type.

For positive numbers, the Int function always rounds down.

For negative numbers, the Int function will return the first
negative integer less than or equal to the original variable value.
- Int(5.6) = 5
- Int(-4.3) = -5

CTA - G. Zucchinetti 29
Rnd Function
• The Rnd[(number)] function will generate a random number.
• The Rnd function returns a value less than 1 but greater than or equal to
zero.
• You can either enter a seed as a parameter for the function, or leave the
seed value blank. The value of number determines how Rnd generates a
random number : Less than zero : the same number every time (using the
seed) ; no number : the next random number in the sequence.
• For any given initial seed, the same number sequence is generated
because each successive call to the Rnd function uses the previous
number as a seed for the next number in the sequence.
• Before calling Rnd, use the Randomize statement without an argument to
initialize the random-number generator with a seed based on the system
timer.
• To create random integers in a specific range, use the formula :
- Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

CTA - G. Zucchinetti 30
Exp Function
The Exp function raises the constant e to some power given in
the function statement.

The value returned will be a double data type.


- Exp(2) = e2 = 7.389056099

CTA - G. Zucchinetti 31
String Functions
There are several string functions available in VBA.

Two useful string functions are UCase and LCase, which can be used
to convert a string into all upper case or all lower case, respectively.
- UCase(string variable or string expression)
- LCase(string variable or string expression)

To extract a segment from a string value, you can use the Mid function.
- Mid(string variable or string expression, starting_position, length)
MidName = Mid(“JohnHenrySmith”, 5, 5)

Another useful string function is Len. This function determines the


length of a string variable value or string expression:
- Len(string variable or string expression)

CTA - G. Zucchinetti 32
Date functions
Three functions in VBA can tell you exactly when it is: the Now, Date,
and Time functions. The Now function returns both the date and time
portions of a Date variable. For example, calling the Now function from
the Immediate window returns a value like this one:
- 2/23/98 6:16:47 PM

The Date function returns the current date. You can use it if you don't
need to know the time. The Time function returns the current time,
without the date.

CTA - G. Zucchinetti 33
Date functions
• To reassemble a date, you can use the DateSerial function. This function
takes three integer arguments : a year, a month and a day value. It
returns a Date value that contains the reassembled date.
• Often you can break apart a date, perform a calculation on it and
reassemble it all in one step. For example, to find the first day of the
month, given any date, you can write a function similar to the following
one :

CTA - G. Zucchinetti 34
Date functions
By using the DateAdd function, you can add any interval to a given
date: years, months, days, weeks, quarters. The following procedure
finds the anniversary of a given date; that is, the next date on which it
occurs. If the anniversary has already occurred this year, the procedure
returns the date of the anniversary in the next year.

CTA - G. Zucchinetti 35
Accessing XL functions with Application Object
• You can use most Microsoft Excel worksheet functions in your Visual
Basic statements.
• To see a list of the worksheet functions you can use, go to :
- http://msdn2.microsoft.com/en-us/library/aa160286(office.10).aspx
• The Application object uses the WorksheetFunction property to set a
function for a cell or range of cells.
• The WorksheetFunction property has several sub properties for almost
all of the Excel functions
- Max
- Min
- Average
- Sum
- Count
- VLookup
- …

CTA - G. Zucchinetti 36
Examples
• Let us use these sub properties of the WorksheetFunction property to
make some more calculations.
• The Application keyword is optional

• Examples :

- Min_salary = Application.WorksheetFunction.Max(salary,3000)
- Insured_salary = Application.WorksheetFunction.Min(salary,106800)
- Av_salary = WorksheetFunction.Average(Worksheets(“pens”).Range("B8:K8"))

CTA - G. Zucchinetti 37
Fetching the content of a single cell

CTA - G. Zucchinetti 38
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 39

You might also like