You are on page 1of 8

The Excel Object Model

Excel Objects and Collection


Excel consists of many objects. VBA is the programming language that interacts with and manipulates
these objects. These objects are organised hierarchically, and can be illustrated as a tree. The Application
object is at the top of the tree it represents Excel itself.
Many of the objects are in collections, but not all (for instance, the Application object is not) the
Application object can be said to contain the other objects in the illustration, some of which are
collections. Collections are objects themselves a collection contains the singular object, e.g. a
collection of Workbooks contains individual Workbook objects. A clue is you can tell a collection because
its name ends with an s (for instance, the Workbooks collection) - though this is not always the case
e.g. Styles. A more reliable indication is that in diagrams the collection is accompanied by the singular
object in brackets (e.g. Workbooks (Workbook)). Figure 1 is a reproduction of part of the object model as
depicted in Help in Excel 2002.

These objects are contained in


the Application object

These objects are contained in


the Workbook object

Figure1

The advantage of looking at the object model is that when writing or recording macro code you will
refer to objects, and it helps to understand where they fit in the scheme of things. The object model is
somewhat large, but most of the objects can be ignored in the first instance, and one can concentrate on
the objects that are fundamental to working with Excel. When an understanding of the general
principles is achieved these principles can be applied to objects that are more peripheral.
Note also the object hierarchy cant be represented easily in a two-dimensional diagram the object
model is a bit more fluid than that. For example, the Windows collection appears twice: once as an
object in the Application object, and once as an object contained in the Workbook object. In the former
case you would say the Application object contains a collection of Windows, and in the latter you would
say the Workbook object contains a collection of Windows. If you are writing a macro with just one
workbook open then both references refer to the same thing. (Note though that in general you dont
work with windows in code, but worksheets and ranges)

Collections
Objects often come in collections e.g. Workbooks.
Figures 2 and 3 illustrate a selection of important collections and objects; Figure 3 explicitly expands
the Collection objects, but conceptually the figures are identical.
Application
Workbooks (Workbook)
Worksheets (Worksheet)

Windows (Window)
Charts (Chart)

Windows (Window)

Range
Figure 2
Application
Workbooks

Windows

Workbook

Window

Worksheets

Charts

Worksheet

Chart

Windows
Window

Range
Figure 3
The way to express either diagram in words is as follows:
The Application object contains a collection of Workbooks; the collection of Workbooks consists of
individual Workbook objects. An individual Workbook object contains (amongst other things) a collection
of Worksheets. The individual Worksheet object contains (amongst other things) individual Range objects.
2

The ideas involved are not simple Collections contain Objects, and Objects contain Collections!
The next illustration shows the objects contained in the Worksheet object.

Figure 4

The Range Object


You will want to refer to cells, rows and columns in your macro code. This is a little more involved. In
each case you use the Range object, but not in the way you might expect at this stage. A range does not
contain a cell or cells (nor rows and columns), rather a range represents (or is) a cell or cells, a row
or rows, a column or columns.
What the Range object does contain is other objects: Areas, Borders, Errors, Interior, Font objects, and so on.
It is not helpful that Help refers to the Range Collection.

is a singular object, and there is no Ranges


collection object. Microsoft say Range represents a cell, a
row, a column, a selection of cells containing one or
more contiguous blocks of cells, or a 3-D range.
Range

It may help to think that a Range object acts like a


collection object that can hold one or more cells, rows or
columns

Figure 5

Object Based systems


In any object-based or object-oriented system it is generally true that an object has three things
associated with it:

Properties
Methods
Events

(an objects properties define the characteristics of the object)


(methods are actions that an object can perform on itself)
(events are changes of state that can be used to trigger a macro to run)

Referring to Objects
In your code you cannot manipulate objects unless you know how to refer to them. There are several
overall concepts to bear in mind:

If there is a default for an object or a property of an object, you can leave it out of the reference
e.g. Range(A1).Value can be shortened to Range(A1)

Some objects, e.g. Workbooks and Worksheets can be referred to by name or by index number.

There are references that are shortcuts, which you wont see explicitly in the object model, e.g.
ActiveWorkbook, ActiveSheet, ActiveCell but they represent a Workbook, Worksheet and Range object
respectively
You can refer to an object explicitly by navigating a path through the hierarchy, e.g.
Application.Workbooks("Week3.xls").Worksheets("Sheet1").Range("G8").Value

but this can be shortened. You would only need to use the Application object in a reference to a
workbook if you were programming outside of Excel, so you can leave it out. Secondly, if you are
referring to a worksheet in the current, or active, workbook, then you can leave out the reference to
the workbook. Thirdly, if you are referring to the current worksheet, you can leave out the reference to
it, so
Range("G8").Value

is a valid reference to the contents of

G8

in the current worksheet.

Writing a value from one workbook to another

As two workbooks cannot be active at the same time you would have to use a full reference for at least
one them in order to write a value from one to the other. Here is an example that uses explicit
references for both:
Workbooks("Week2.xls").Worksheets("Introductory").Range("A1")= _
Workbooks("Week3.xls").Worksheets("Sheet1").Range("G8")

Remember, both workbooks would have to be open.


Select method / Activate method

Typically a program selects/activates an object before setting its properties. The Activate or Select method
can be used interchangeably, except in the case of a workbook, where you must use Activate, using Select
results in an error. Here are some examples:
Workbooks("Week2.xls").Activate
Workbooks(2).Activate
Worksheets("Sheet1").Activate
Workshets("Sheet1").Select

activates a workbook referring its name


activates the second workbook to have been opened

activates/selects a worksheet named Sheet1 in the


active workbook
4

selects second sheet in the active workbook


the second worksheet in the second workbook
selects cell B3 on the active sheet

Worksheets(2).Select
Workbooks(2).Worksheets(2).Activate
Range("B3").Select

Since Excel 2007/2013 the statement below fails:


Worksheets("Sheet1").Range("B3").Select

so you would have to write two lines:


Worksheets("Sheet1").Select
Range("B3").Select

However, Worksheets("Sheet1").Range("B3") = 88

is ok

Referring to ranges
There is a variety of notations for the range object, because a range can be a cell or cells, a row, a
column and so on.
When you want to refer to a two-dimensional range you have the following options:
Range("A1:C5").Select
Range("A1","C5").Select

cells A1:C5 on the active sheet


as above, using top left and bottom right corners

also there are the less commonly used


Range("D1:E1, G1:J5").Select
Range("A2:F3 A1:D5").Select

a union
an intersection

References to named ranges follow the same pattern:


Range("ExamMarks").Select

refers to a named range called ExamMarks

Objects have Properties


An objects properties define the characteristics of an object. A Worksheet has a Name property, a Visible
property, a Range has a Value property, a Locked property and many others. Collection objects also have
properties too, but different properties to the singular object. The collection of worksheets has a Count
property, whose value is the number of worksheets in the workbook the Count property is read-only,
but other properties are easy to change. The syntax is object.property e.g.
Worksheets.Count

In code you may want to set an objects property, or else you may want to get the value of an
objects property, i.e. find out what it is and perhaps use it in your code..
Setting a property
To set a property it is you type the reference on the left hand side of an equals sign and on the right
hand side you type the new setting, e.g.,
Worksheets(1).Visible = False
Range("A9").Value = "Fixed Assets"
Range("B10").Value = 23000

You can assign the result of, say, adding two cells as follows:
Range("A3").Value = "=A1+A2"
Range("A3").Formula = "=A1+A2"

The value property and the formula property are interchangeable


In both cases A3 ends up containing the formula =A1+A2

Similarly the expression


5

Range("A3").Value = "=Average(A1:A2)"

would literally place the function in cell A3


Formatting Properties - examples

The Font object has many properties that format


the contents of a cell.

Range("A3:A5").Font.Bold = True
Range("A3:A5").Font.Italic = True
Range("A3:A5").Font.Name = "Arial"
Range("A3:A5").Font.Size = 9
Range("A3:A5").Font.Color = vbRed
Range("A3:A5").Interior.Color = vbYellow

The Interior object is the background of a cell

Formatting Numbers
The 0 (zero) placeholder displays insignificant zeros. E.g., if you want 8.9 to be displayed as 8.90, use
the format #.00
The # placeholder does not display extra zeros. E.g., if the format is #.##, and you type 8.90 in the cell,
the number 8.9 is displayed.
Examples
Selection.NumberFormat = "$#,##0.00"
Selection.NumberFormat
Selection.NumberFormat
Selection.NumberFormat
Selection.NumberFormat

=
=
=
=

"$#,##0"
"[$$-409]#,##0.00"
"[$-2] #,##0.00"
"@"

Displays currency symbol, commas are


thousands separators, and 2 decimal places
As above, with no decimal places
US dollars (as recorded)
Euro symbol, as recorded
Number appears as typed, e.g. phone
numbers like 0800

Getting a property
To get a property you type a variable on the left hand side of an equals sign, and on the right hand
side you type a reference to the property. e.g.,
subTotal = Range("A3").Value
where subTotal is a suitably declared

variable

Objects have Methods


A method is an action that an object can perform on itself. The syntax is object.method
The most basic method is to select an object, e.g.
Range("A1:C5").Select
Range("ExamMarks").Select
Worksheets("Sheet1").Select

or Worksheets("Sheet1").Activate

You dont use Select with a workbook, there is only Activate. The book must already be open.
Workbooks("Week2.xlsx").Activate
Workbooks("Week2").Activate also works

if there is no ambiguity with the file extension.

Some methods take arguments these arguments may or may not be compulsory. For example, if you
use the Workbooks.Open method you must provide a filename or valid reference to a filename e.g.
Workbooks.Open "D:\Spreadsheets\Myfile.xls"

On the other hand the Close method takes an optional argument compare the following examples:
Workbooks(2).Close
Workbooks(2).Close False
Workbooks(2).Close True

will prompt to save changes


closes without saving changes
closes and saves changes

More examples of methods


Range("A1:B3").Clear
Selection.Clear
Selection.ClearFormats
Worksheets.Add
Workbooks.Add
Save

clears the contents of specific cells on the active sheet


a more general statement that clears the contents of selected cells
clears formatting from selected cells
adds a new worksheet
creates a new workbook

is a method of the workbook, so the following are possible

ActiveWorkbook.Save
ThisWorkbook.Save

As you might expect SaveAs requires an argument, the filename to save to:
Workbooks("Week3.xls").SaveAs "CopyOfWeek3.xls"
Named arguments vs arguments by position

Usually the QuickList is visible to aid you when a method has properties, and arguments can be used by
position. There is also the option of using named arguments, e.g.
Workbooks("Week3.xls").SaveAs Filename:="CopyOfWeek3.xls",Password:= "Elephant"

This is of course much more typing, but has two virtues:


- the arguments can be in any order you like
- the code is self documenting
Properties that represent Objects
The Application object provides properties that return a range object, e.g. ActiveCell, Selection. Essentially
they are shortcuts that look like they are objects in their own right, and can be used as such.
ActiveCell

is a property of the Application or Window object that returns a range representing the active cell.
Examples:
ActiveCell

ActiveCell = 23
ActiveCell.Font.Bold = True

Selection

The Selection object is actually a property of the Application or Window object which returns a Range
object; therefore you can use Selection as a valid reference to a Range, and use the Range objects
properties and methods according to the same rules. For example, the two statements:
Range("A1:B3").Select
Selection.Clear

are equivalent to

Range("A1:B3").Clear

Be careful to distinguish between the active cell and the selection. The active cell is a single cell. If
one cell is selected then ActiveCell and Selection are equivalent. The selection may contain more than one
cell, but only one is the active cell.
Property
When a worksheet is the active sheet, you can use the ActiveSheet property to refer to it. ActiveSheet is a
property of the Application, Window or Workbook object that returns a worksheet. The following example
uses the Activate method to activate a worksheet, sets the page orientation to landscape mode, and then
prints the worksheet:
ActiveSheet

Worksheets("Sheet1").Activate
ActiveSheet.PageSetup.Orientation = xlLandscape
ActiveSheet.PrintOut

Rows and Columns


Rows and columns are properties of the Worksheet, Range or Application object that return a Range object
you wont find them in the Object Model.
Rows and columns as properties of the Worksheet

In the context of a worksheet simply refer to rows or columns by using an index number e.g.
Rows(3).Select
Columns(2).Select

Using this syntax is equivalent to using ActiveSheet.Rows or ActiveSheet.Columns


This is how the macro recorder handles selecting a single row or column:
Rows("3:3").Select
Columns("B:B").Select

Multiple rows or columns are referenced as follows:


Columns("B:E").Select
Rows("3:8").Select

However, syntax such as


does not work. The Application object has a Union method, though,
which you could use to accomplish this kind of thing.
For example,
Columns("B:E", "H:J").Select

Union(Columns("B:E"), Columns("H:J")).Select

or even
Union(Columns(2), Rows(4)).Select

Sometimes a method requires a reference to a range that is a column or a row e.g.


Columns("A:D").AutoFit

or more generally
Selection.EntireColumn.AutoFit

but
Selection.Autofit

or Range("A1:D4").Autofit would both be invalid.

Rows and columns as properties of a Range

More usefully Rows and Columns can be referred to in the context of a range. For example
Selection.Rows(1).Select selects the first row of the current selection.
Selection.Rows(1).Font.Bold = True boldfaces the first row of a selection.
Columns can be referred to in the same way; here are further examples:
Selection.Columns(1).Select selects the first column of the currently selected cells.
Selection.Columns(1).Font.Italic = True italicizes the first column of a selection.
The Count Property
The Count property is able to return the count of members of a collection
Rows.Count returns the count of rows in the entire worksheet
Columns.Count returns the count of columns in the entire worksheet
References to Rows/Column as properties of a range can be more useful, e.g.,
Selection.Rows.Count returns the count of the rows in a selection.
Selection.Columns.Count returns the count of the columns in a selection.

You might also like