You are on page 1of 42

Collections & Excel’s Object

Model

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

1. Collections
2. Browsing the Excel Object Model
3. Using the Excel Object Model with Macros
Collections

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Collections & Excel
In the Excel Object Model, many elements are part of a
collection.

This is a collection of all of the Worksheet objects in a workbook


(or to be more exact, all of the objects in the Worksheets
collection, which is contained within the workbook). There are 3
objects in the collection.
An object is a single thing in a collection. For instance :
- Worksheets ("Sheet1")

CTA - G. Zucchinetti 4
Collection of objects - Definition
• A Collection object is an ordered set of items that can be referred to as
a unit.
• The Collection object provides a convenient way to refer to a related
group of items as a single object. The items, or members, in a
collection need only be related by the fact that they exist in the
collection. Members of a collection don't have to share the same data
type.
• A collection can be created in VBA the same way other objects are
created. For example :
- Dim X As New Collection
• Once a collection is created, members can be added using the Add
method and removed using the Remove method. Specific members
can be returned from the collection using the Item method, while the
entire collection can be iterated using the For Each... Next statement.

CTA - G. Zucchinetti 5
Declaration - Example

Sub test_collection()
Dim theEmployees As Collection
Dim emp As CEmployee
Dim row As Integer
Dim idInput As String

Set theEmployees = New Collection

CTA - G. Zucchinetti 6
Add - Method
• Adds an item Object to a Collection object.
- Syntax : collectionObject.Add item, key, before, after
• collectionObject (required) : an object expression that refers to the
collection to receive a new item object.
• item (required) : an expression of any type that specifies the
member to add to the collection.
• key (optional) : a unique string expression that specifies a key string
that can be used, instead of a positional index, to access a member
of the collection.
• Before / After (optional) : an expression that specifies a relative
position in the collection. The member to be added is placed in the
collection before (after) the member identified by the before (after)
argument.
• An error occurs if a specified key duplicates the key for an existing
member of the collection.

CTA - G. Zucchinetti 7
Add - Example
Do While Worksheets("employees").Cells(row, 1) <> ""
Set emp = New CEmployee
With emp
.ID = Worksheets("employees").Cells(row, 1)
.name = Worksheets("employees").Cells(row, 2)
.birthDate = Worksheets("employees").Cells(row, 3)
.gender = Worksheets("employees").Cells(row, 4)
.grossSalary = Worksheets("employees").Cells(row, 5)
End With

Call theEmployees.Add(emp, emp.ID)


Set emp = Nothing
row = row + 1
Loop

CTA - G. Zucchinetti 8
Item - Method
• Returns a specific member of a Collection object either by position
or by key.
- Syntax : collectionObject.Item(index)
• collectionObject (required) : an object expression that refers to the
collection to receive a new item object.
• index (required) : an expression that specifies the position of a
member of the collection. If a numeric expression, index must be a
number from 1 to the value of the collection's Count property. If a
string expression, index must correspond to the key argument
specified when the member referred to was added to the collection.
• If the value provided as index doesn't match any existing member of
the collection, an error occurs.
• The Item method is the default method for a collection. Therefore,
the following lines of code are equivalent:
- Print MyCollection(1)
- Print MyCollection.Item(1)
CTA - G. Zucchinetti 9
Item - Example

MsgBox theEmployees(2).name

Or MsgBox theEmployees.Item(2).name

MsgBox theEmployees("d3").name

Or MsgBox theEmployees.Item("d3").name

CTA - G. Zucchinetti 10
Remove - Method
• Removes a member from a Collection object
- Syntax : collectionObject.Remove index
• collectionObject (required) : an object expression that refers to the
collection to receive a new item object.
• index (required) : an expression that specifies the position of a
member of the collection. If a numeric expression, index must be a
number from 1 to the value of the collection's Count property. If a
string expression, index must correspond to the key argument
specified when the member referred to was added to the collection.

• If the value provided as index doesn't match any existing member of


the collection, an error occurs.

CTA - G. Zucchinetti 11
Remove - Example

idInput = InputBox("Employee ID to remove : ")

theEmployees.Remove (idInput)

CTA - G. Zucchinetti 12
Count - Property
Syntax : collectionObject.Count

Returns the number of items in the collection.

Example : MsgBox "Number of employees in the collection : " &


theEmployees.Count

CTA - G. Zucchinetti 13
Looping on a Collection of
Employees

For Each emp In theEmployees


Debug.Print emp.name & " " & emp.currentAge
Next emp

CTA - G. Zucchinetti 14
Browsing the Excel
Object Model

HEC Lausanne
Computanional Tools for Actuaries (CTA)
The Excel Object Model
Every application which uses VBA has its own object model. So
(for example) here are some of the collections in different object
models :

Application Typical collections

Word Words, Documents, Paragraphs,


Characters
Excel Worksheets, Workbooks,
PivotTables
PowerPoint Presentations, Slides, Shapes

CTA - G. Zucchinetti 16
Excel Object Model - Overview

CTA - G. Zucchinetti 17
Browsing the Object Model
VBA Excel Help :
https://msdn.microsoft.com/en-us/library/office/ee814737(v=office.14).aspx

VBA Object browser :

But it’s more intuitive to record


macros and then generalize them

CTA - G. Zucchinetti 18
Using the Excel Object Model
with Macros

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Macros
• Recording Macros

• The VBA Code

CTA - G. Zucchinetti 20
Recording Macros
Macros are technically defined as units of VBA code.

Macros can be thought of as a way to automate a series of


actions in a spreadsheet application.

Macros can either be created directly with VBA code in the


Visual Basic Editor, or recorded in Excel.

To record a macro, we must know exactly the actions we wish to


perform and then use the Macro Recorder.

CTA - G. Zucchinetti 21
Example 1
Let us record a macro which copies and pastes data.

A dealer wants to send the information from the first three columns and last
column of the data table to the newspaper.

CTA - G. Zucchinetti 22
Preparation
First we should review/practice the steps we will take when
recording the macro
- Highlight the first three columns of data with the cursor (C4:E13)
- Copy (using CTL+C, right-click and Copy, or the Edit option)
- Place the cursor in cell C19
- Paste (using CTL+P, right-click and Paste, or Edit option)
- Highlight the last column (K4:K13)
- Copy
- Place cursor in cell F19
- Paste

CTA - G. Zucchinetti 23
Record
Now we are ready to record the macro
-Tools → Macro → Record New Macro or click on start button
-Record button from VBE Toolbar

When the Record Macro dialog box appears, we enter a name for the
macro.

CTA - G. Zucchinetti 24
Stop
Once you begin recording, notice that the Record button transforms to a
Stop button.

After finishing the steps needed to copy and paste the information, you can
stop recording.
-Tools → Macro → Stop Recording Macro or click on stop button
-Stop button from VBE Toolbar

CTA - G. Zucchinetti 25
Play
Once you have recorded a macro, you can play it to ensure it works
correctly.
- Tools → Macros → Macros or click on the macros icon
- Play button from VBE Toolbar

CTA - G. Zucchinetti 26
Result
We can see that the macro works correctly.

CTA - G. Zucchinetti 27
VBA Code
As we learned earlier, each time a macro is recorded in Excel,
VBA code is automatically generated.

Let us review what code was generated for this macro


- Go the VBE window
- A module has been created in the Project Explorer
- Select the module to see the code in the Code Window

CTA - G. Zucchinetti 28
VBA Code
• This is the initial statement of the
Sub CarCopyPaste() sub procedure.
– The Select method of the
Range("C5:E14").Select Range object selects the
Selection.Copy specified range of cells.
Range("C20").Select
– The Copy method is used on
ActiveSheet.Paste
the Selection object.
Range("K5:K14").Select – The Paste method is used on
Selection.Copy the ActiveSheet object.
Range("F20").Select – These steps are repeated to
ActiveSheet.Paste copy and paste the last column.
– This last cell selection can be
Range("A1").Select added to avoid leaving the cells
highlighted.
End Sub

CTA - G. Zucchinetti 29
Starting in VBA
• Since we can study the VBA code generated when we record a
macro, we can easily by creating a similar macro directly from
VBA by copying the code generated and adapting it.

• We will now learn how to use Sort and Filter functions in VBA by
first recording a macro and then using the generated VBA code
to create similar macros starting in VBA.

CTA - G. Zucchinetti 30
Example 2
Suppose there is a database for the
Miami Airport which lists Flight
Destinations, Number of Stops, Class
and Price.

We want to be able to filter this


information so that we can do the
following:
- View flights to Beijing
- View flights to Hong Kong
- View all flights

We also want to be able to sort the


data by
- Number of Stops
- Price

CTA - G. Zucchinetti 31
Filtering
We will begin by recording the macro to filter the data for
viewing Beijing flights only.

To prepare for recording a macro to filter the data table, we


review the steps we will perform
- Highlight all data (B3:E15)
- Data → Filter → AutoFilter
- Select the drop-down button for “Destination” column
- Filter for Beijing flights
- Select cell A1

CTA - G. Zucchinetti 32
Excel to VBE
We can check this recorded macro to ensure it works.
Now we can go to VBE to view the code generated.

CTA - G. Zucchinetti 33
Creating New Code
Now that we know the basic structure of the code, we can simply modify it to
accomplish the other filtering macros.

• The Sub titles will change for each


Sub ViewBeijingFlights()
new macro
– The AutoFilter method will be
Range("B3:E15").Select used on the same selection to
Selection.AutoFilter generate the filtering drop-
Field:=1, down arrows
Criteria1:="Beijing" – Field:=1 denotes the
Range("A1").Select “Destination” column, we can
modify this value
End Sub – Criteria1:=“Beijing” is the value
which is filtered, we can also
modify this value

CTA - G. Zucchinetti 34
New Macros from VBA
We can now create a macro to view Hong Kong flights and view All flights
by using the code from the recorded macro.

------------------------------------------------------
Sub ViewHongKongFlights()
Range("B3:E15").Select
Selection.AutoFilter Field:=1, Criteria1:="Hong Kong"
Range("A1").Select
End Sub
------------------------------------------------------
Sub ViewAllFlights()
Range("B3:E15").Select
Selection.AutoFilter Field:=1
Range("A1").Select
End Sub
------------------------------------------------------

CTA - G. Zucchinetti 35
Understanding the components
go to a specific open workbook by name
- Workbooks("test.xlsm").Activate
go to the first worksheet in it
- Worksheets(1).Select
put words in the top left cell
- Range("A1").Value = ”Hello World"

Part What it is

Workbooks This is a collection, but ...

Workbooks("test.xlsm") ... this is an object within the


collection
Activate A method (something you do to
a workbook)
Select Another method (something
you do to a worksheet)
Range("A1") An object (of type Range)

Value A property of a range which


tells you what it contains
CTA - G. Zucchinetti 36
Sorting
• We will now record a macro to sort the data by number of
stops.

• To prepare for recording a macro to sort the data table, we


review the steps we will perform
- Highlight all data (B3:E15)
- Data → Sort
- Select “Stops” from the Sort by list
- Select Descending as the order
- Select cell A1

CTA - G. Zucchinetti 37
Excel to VBA
We can check this recorded macro
to ensure it works.

Now we can go to the VBE to view


the code generated.

CTA - G. Zucchinetti 38
Creating New Code
Now that we know the basic structure of the code, we can simply
modify it to accomplish the other sorting macros.

Sub SortByStops() • The Sub titles will change for each


new macro
Range("B3:E15").Select – The Sort method will be used
Selection.Sort on the same selection
Key1:=Range("C4"), – Key1:=Range(“C4”) denotes
Order1:=xlDescending the “Stops” column
Range("A1").Select – Order1:= xlDescending is the
order in which the data will be
sorted
End Sub

CTA - G. Zucchinetti 39
New Macro from VBA
We can now create a macro to sort by price by using the code
from the recorded macro.

------------------------------------------------------
Sub SortByPrice()
Range("B3:E15").Select
Selection.Sort Key1:=Range("E4"), Order1:=xlDescending
Range("A1").Select
End Sub
------------------------------------------------------

CTA - G. Zucchinetti 40
Summary
• Macros are technically defined as units of VBA code.
• Macros can either be created directly with VBA code in the
Visual Basic Editor, or recorded in Excel.
• Steps to Record a Macro:
1. Choose Tools → Macros → Record New Macro or choose the
Record icon from the VBA toolbar;
2. Perform a sequence of actions in Excel;
3. Choose Tools → Macros → Stop Recording or choose the Stop
icon from the VBA toolbar.
• Macros can be generalized directly from VBA

CTA - G. Zucchinetti 41
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 42

You might also like