vba course

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

Upload: etulan-adu

Post on 14-Jan-2016

219 views

Category:

Documents


3 download

DESCRIPTION

Learn VBA

TRANSCRIPT

Page 1: VBA Course

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.

Figure1

1

These objects are contained in

the Application object

These objects are contained in

the Workbook object

Page 2: VBA Course

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 can’t 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 don’t work with windows in code, but worksheets and ranges)

CollectionsObjects 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) Windows (Window)

Worksheets (Worksheet) Charts (Chart) Windows (Window)

RangeFigure 2

Application

Workbooks Windows

Workbook Window

Worksheets Charts Windows

Worksheet Chart Window

RangeFigure 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

Page 3: VBA Course

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

3

Page 4: VBA Course

Figure 5

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

Properties (an object’s properties define the characteristics of the object) Methods (methods are actions that an object can perform on itself) Events (events are changes of state that can be used to trigger a macro to run)

Referring to ObjectsIn 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 won’t 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 anotherAs 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 methodTypically 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 activates a workbook referring it’s name Workbooks(2).Activate activates the second workbook to have been openedWorksheets("Sheet1").ActivateWorkshets("Sheet1").Select

activates/selects a worksheet named Sheet1 in the active workbook

4

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

It may help to think that a Range object acts like a collection object that can hold one or more cells,

Page 5: VBA Course

Worksheets(2).Select selects second sheet in the active workbookWorkbooks(2).Worksheets(2).Activate the second worksheet in the second workbookRange("B3").Select selects cell B3 on the active sheet

Since Excel 2007/2013 the statement below fails:Worksheets("Sheet1").Range("B3").Select

so you would have to write two lines:Worksheets("Sheet1").SelectRange("B3").Select

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

Referring to rangesThere 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 cells A1:C5 on the active sheetRange("A1","C5").Select as above, using top left and bottom right corners

also there are the less commonly used

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

References to named ranges follow the same pattern:

Range("ExamMarks").Select refers to a named range called ExamMarks

Objects have Properties

An object’s 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 object’s 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 propertyTo 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 = FalseRange("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

Page 6: VBA Course

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

would literally place the function in cell A3

Formatting Properties - examplesRange("A3:A5").Font.Bold = TrueRange("A3:A5").Font.Italic = TrueRange("A3:A5").Font.Name = "Arial"Range("A3:A5").Font.Size = 9Range("A3:A5").Font.Color = vbRed

Range("A3:A5").Interior.Color = vbYellow

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

ExamplesSelection.NumberFormat = "$#,##0.00" Displays currency symbol, commas are

thousands separators, and 2 decimal placesSelection.NumberFormat = "$#,##0" As above, with no decimal placesSelection.NumberFormat = "[$$-409]#,##0.00" US dollars (as recorded)Selection.NumberFormat = "[$€-2] #,##0.00" Euro symbol, as recordedSelection.NumberFormat = "@" Number appears as typed, e.g. phone

numbers like 0800…

‘Getting’ a propertyTo ‘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").SelectRange("ExamMarks").Select

Worksheets("Sheet1").Select or Worksheets("Sheet1").Activate

You don’t 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 ‘will prompt to save changes

Workbooks(2).Close False ‘closes without saving changes

Workbooks(2).Close True ‘closes and saves changes

More examples of methods

6

The Font object has many properties that format the contents of a cell.

The Interior object is the background of a cell

Page 7: VBA Course

Range("A1:B3").Clear Selection.Clear

clears the contents of specific cells on the active sheeta more general statement that clears the contents of selected cells

Selection.ClearFormats clears formatting from selected cellsWorksheets.Add adds a new worksheetWorkbooks.Add creates a new workbook

Save is a method of the workbook, so the following are possibleActiveWorkbook.SaveThisWorkbook.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 positionUsually 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.

ActiveCellActiveCell is a property of the Application or Window object that returns a range representing the active cell.Examples: ActiveCell = 23 ActiveCell.Font.Bold = True

SelectionThe 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 object’s 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.

ActiveSheet PropertyWhen 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:Worksheets("Sheet1").ActivateActiveSheet.PageSetup.Orientation = xlLandscapeActiveSheet.PrintOut

7

Page 8: VBA Course

Rows and ColumnsRows and columns are properties of the Worksheet, Range or Application object that return a Range object – you won’t find them in the Object Model.

Rows and columns as properties of the WorksheetIn 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 asColumns("B:E", "H:J").Select does not work. The Application object has a Union method, though, which you could use to accomplish this kind of thing.For example,Union(Columns("B:E"), Columns("H:J")).Select

or evenUnion(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 generallySelection.EntireColumn.AutoFit

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

Rows and columns as properties of a RangeMore usefully Rows and Columns can be referred to in the context of a range. For exampleSelection.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 PropertyThe Count property is able to return the count of members of a collectionRows.Count returns the count of rows in the entire worksheetColumns.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.

8