VBA Course
VBA Course
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
Figure 5
Properties
Methods
Events
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
G8
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")
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
Worksheets(2).Select
Workbooks(2).Worksheets(2).Activate
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
a union
an intersection
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"
Range("A3").Value = "=Average(A1:A2)"
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
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"
"@"
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
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
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
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"
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
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
Union(Columns("B:E"), Columns("H:J")).Select
or even
Union(Columns(2), Rows(4)).Select
or more generally
Selection.EntireColumn.AutoFit
but
Selection.Autofit
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.