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 eg SmartTagOptions. 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 1 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) Collections Objects often come in collections eg. 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 Worksheet Charts 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 2 collection of Worksheets. The individual Worksheet object contains (amongst other things) individual Range objects. The ideas involved are not simple – Collections contain Objects, and Objects contain Collections! What does the Workbooks collection contain? It contains individual Workbook objects Figure 4 You can use Help to explore in more detail. Click the Workbook object box. Other objects also contain the Workbook object: Application Figure 5 object, RecentFile object, Workbooks collection. a workbook contains many objects e.g. Names collection, Worksheets collection, Sheets collection, Styles collection, Chart object, Windows collection. What does the individual Worksheet object contain? Again, multiple objects, e.g. the collection of Names, Range objects (note there is no Ranges collection object). Figure 6 Figure 7 reproduces the contents of the Worksheet object from Excel 2002 Help Again there is a large number of objects – you will want to work with Range and Names objects sooner rather than later, the PageSetup object is useful to control printing. 3 Figure 7 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 may be confusing that Help refers to the ‘Range Collection’. is a singular object, and there is no Ranges collection object. Help says 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 Figure 8 It may help to think that a Range object acts like a collection object that can hold collections of cells, collections of row, collections of columns 4 Object References In your code you cannot manipulate objects unless you know how to refer to them. There are several overall concepts to bear in mind: 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, eg. ActiveWorkbook, ActiveSheet, ActiveCell but they represent a Workbook, Worksheet and Range object respectively If there is a default for an object or a property of an object, you can leave it out of the reference You could refer to an object by name by navigating a path through the hierarchy, e.g. Application.Workbooks("prices.xls").Worksheets("Sheet1").Range("A1").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("A1").Value is a valid reference to the contents of A1 in the current worksheet. Here are some more examples: Workbooks("d:\spreadsheets\prices.xls") Workbooks(2) Worksheets(“Sheet1”) Worksheets(2) Workbooks(2).Worksheets(2) Worksheets("Sheet1").Range("B3") Range(“B3”) specify the pathname as a string if you want to open it the second workbook to have been opened a worksheet named Sheet1 in the active workbook the second sheet in tab order in the active workbook the second worksheet in the second workbook cell B3 on the particular sheet in the reference cell B3 on the active sheet 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") Range("A1","C5") 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") Range("A2:F3 A1:D5") a union an intersection See ‘Properties that represent Objects’ for more examples of using Ranges. 5 Objects have Properties An object’s properties define the characteristics of an object. A Worksheet has a Name property, a Visible propery, 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 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 Objects can have default properties; when you refer to a range that is a single cell, then its default property is Value. Therefore in code you could shorten the line Range("A1").Value = 50 to Range("A1") = 50 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 mostly interchangeable In both cases A3 has the formula =A1+A2 Similarly Range("A3").Value = "=Average(A1:A2)" would literally place the function in cell A3 Range("A3:A5").Font.Bold = True Range("A3:A5").Interior.ColorIndex = 4 Range("A3:A5").Interior.Color = vbYellow Note there is often more than one property to accomplish the same thing – the ones that require an integer value, like ColorIndex, tend to be older ones retained for backwards compatibility. More modern ones take a constant i.e. vbYellow in the example – which one would you prefer to try and remember? ‘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 Workbooks.Add Range("A1:B3").Clear Selection.Clear Worksheets("Sheet1").Activate 6 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: 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 Properties that represent Objects Often the Excel Object Model provides a property that returns an object. Many of these techniques are to do with ranges – in Excel ranges consist of cells, or rows or columns, or 3D ranges; ranges can have names, a range may or may not be selected at a given moment. Therefore there is more variation available than the Range(“A1”) syntax we have been using so far. 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 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 ActiveCell is a property of the Application or Window object that returns a range representing the active cell. The following expressions all return the active cell, and are all equivalent: ActiveCell ActiveCell Application.ActiveCell ActiveWindow.ActiveCell Application.ActiveWindow.ActiveCell Naturally use the shortest! Examples: ActiveCell.Value = 23 ActiveCell.Font.Bold = True Be careful to distinguish between the active cell and the selection. The active cell is a single cell inside the current selection. 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. ActiveSheet 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").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 won’t find them in the Object Model. You can simply refer to rows or columns by using an index number e.g. Rows(3).Select 7 Columns(2).Select Using this syntax is equivalent to using 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 Columns("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(2), Columns(4)).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 but Selection.Autofit or Range("A1:D4").Autofit would both be invalid. Cells Again, there is no official Cells collection nor a Cell object, but the Cells property acts as though it returns a cells collection as a Range object. A reference to Cells is a reference to a property of the Worksheet, Range or Application object that returns a Range object. When used with a Range object the Cells property returns the same object so effectively does nothing: Range("A1:D8").Cells.Count Range("A1:D8").Count are equivalent. You can use the syntax Cells(i,j) which would return the cell at row i and column j. For example Worksheets("Sheet1").Cells(5,3).Clear clears the contents of row 5 column 3, i.e. cell C5 This example uses a row and column index i.e. 5 and 3. If only one number is supplied e.g. Worksheets("Sheet1").Cells(1).Clear then the first cell on the worksheet is cleared i.e. cell A1. NB: Cells(2) would refer to B1 – the index moves across the columns – as there are 256 columns Cells(257) would reference cell A2. Using the Cells property without an object qualifier returns a Range object that represents all the cells on the active worksheet e.g. Cells.Count returns 16777216 (the number of cells on a worksheet.) In fact Cells Application.Cells ActiveSheet.Cells are all equivalent statements. This example sets the font and font size for every cell on Sheet1 to 8-point Impact. With Worksheets("Sheet1").Cells.Font .Name = "Impact" .Size = 8 End With 8