The Excel Object Model provides you additional commands than you would normally obtain from the Excel menu of commands and functions. Almost anything you can do with Excel from its user interface, you can do by manipulating its objects through VBA. Microsoft has empowered you with all the objects and methods so you can do anything through VB code that can't be done through the Excel user interface. Examples of objects in the Excel Object Model are Workbooks, Worksheets, Range, Cells, Charts, Pivot and Comments. Excel is a three-tier application: client services tier, object model, and data services layer. The workbook interface that user usually communicate with is the client services tier. Underneath this lays the object model. Each time you do something on your worksheet, you are issuing commands through the Excel object model. You use the object model to communicate with Excel application by manipulating the properties and methods of the various objects. For example, if you select File/Open from Excel menu, you are using the command Workbooks.Open to open your workbook, Sheets.Add to insert a new worksheet [see example], and add it to the workbooks collection object. Similarly, if you select Tool/Options and in Options dialog box to set Calculation to manual and using F9 to recalculate, you are issuing the command Application.Calculate [see example]. Below the object model sits the data services layer, which hold data in the spreadsheet and is modified by commands from the Excel object model.
The following example demonstrates the concept of object. (In fact you do not have to explicitly refer to the Application object as shown in line 2). Cell A1 has a Value property that shows 10. If cell B1 has a formula, a message will display cell B1 address, else it will do nothing. Address property cannot be changed. Cell B1 will have the Address of $B$1 no matter what you do. Value is a read/write property. Cell content of A1 is cleared, and B1 formula will be copied over to A1. The last line makes A1 an active cell.
Dim ad As String Objects are arranged in hierarchy. For example, at the top of the Excel object model is the Application object, and under which is the Workbook object. Within each Workbook object are the Range objects, Cells objects, and so on. Each object can contain settings or attributes called properties, and actions that can be performed on the object called methods, or both. In example line 1 below, you specify a range of cells A1:A10 in the range property and use the value property to place the text "Welcome to VBA" in these cells. In line 2, you copy the range of cells in the Activecell column and paste it into range B1:B10 in Sheet2.
Worksheets("Sheet1").Range("A1:A10").Value
= "Welcome to VBA" Excel exposes various other
creatable objects, allow you to do other more amazing things with these objects.
These are some of the other commonly used key objects:
‘ if you close
the workbook, you will still be prompted for saving even changes had already
been saved
‘ this example
creates a new worksheet and then sets its Visible property to xlVeryHidden. To
use the newSheet object variable in another procedure, you must declare it as a
public variable (Public newSheet As Object). Properties can be either read-only or read/write. HasPassword property in Workbook shows True or False according to whether the workbook is protected by a password. HasPassword property is read-only as you can’t change it to False to remove password protection without knowing the password. The Count property of the Workbooks object defines how many workbooks are loaded into the Excel application, and is read-only. For example, a workbook contains three worksheets and if you could change the Count property to one sheet, the other two sheets of data would be deleted. If a property is read-write, it means you can substitute values into it to provide different effects, depending on the object. If ActiveWorkbook.HasPassword = True Then Properties can be manipulated by using code at runtime when the program is executing and can be changed at design time using properties window in VBE. The following is an example of changing property at design time. The open Workbook is the object and Saved is the property. There is more than one dot separator because objects can have subobjects and properties can have subproperties. The workbook Saved property is set to True and it means you will not get prompted for saving regardless of whether it has been saved or not. In the example below, you place this code in ThisWorkbook’s SheetChange event, and every time you make changes to the data in the worksheet, the Saved property will be set back to True. When you close the worksheet, there is no prompt to save because the program will check the Saved property of your worksheet called Sheet1 and set it to True and assume that it is already saved.
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target
As Range)
‘ this opens
MyWorkbook.xls from C directory
Workbooks("Book1").SaveAs "C:\Mybook1.xls", , "kuching", ,True An alternative way is passing by name method. Passing parameters by name enables you to selectively pass arguments without having to specify null values for arguments you don not want to use. In this method, you can pass the parameters in any order. With this method, the preceding example will be re-written as follow:
Workbooks("Book1").SaveAs Filename:="C:\Mybook1.xls", _
To explain in another way, the Application object has a property called Workbooks, which represents a Workbooks Collection object. It includes a single Workbook object for each workbook currently open in Excel. Similarly, the Workbooks object has a property called Worksheets which is a Worksheets Collection object, including one Worksheet object for each worksheet in the workbook. Collections also have their own properties and methods apart from the objects that they hold. For example, Collections have a Count property that represents the number of objects within the collection, and also have an Add method that adds a new object into the collection.
Referencing Items in a Collection
Option
Explicit Remember this: Objects are things in Excel; Properties are characteristics that define those objects; and Methods are actions that the objects take and that change a few properties along the way. The structure of Excel object model is complicated and you should not be expected to remember every object, collection, property and method within it. If you do not use the automatic list boxes that appear as you type object code in, you will have to constantly refer to Object Browser in order to know what command to use next. In the Object Browser, click a class (which is an object) to see all the collection, property and method within it in the Members of Lists box to the right of class. Methods have a green icon (clicking a method display the syntax for parameters, which ones are optional and mandatory), and properties have a grey icon with a hand symbol holding it (clicking a property will show whether it is read-only or if you can write to it). You can get an overview of the Microsoft Excel Object Model by going to VBE, choose Help/ Microsoft Visual Basic Help. Type excel object model in search box, press Enter. In the search result, click Microsoft Excel Object Model, and you will able to see an overview screen of the Excel Object Model. The yellow shaded boxes are objects that are organized into collections, while the blue shaded boxes are objects that do not have collections. You can click a box to display the Help screen for an individual object or collection including a schematic of the related objects. For example, click on the blue shaded Workbook object will display the related properties.
Application Object ScreenUpdating, DisplayAlerts, UserName, CutCopyMode… Methods: CheckSpelling, Run, Quit… Collections: Rows, Columns, Sheets…
‘ActiveCell
property represents the active cell the cursor is currently at
Methods: Activate, Save, SaveAs, Close, Protect, PrintOut, PrintPreview…
‘ Activate
method activates the workbook specified in the Collection object
' To exit a
worksheet without saving any changes that are made to it
Methods: Activate, Select, Calculate, Copy, Add, Delete, Move, PrintOut, Protect, Unprotect, SaveAs… Collections: Comments… ' this Activate method makes the 1st worksheet the active worksheet Worksheets(1).Activate ' Name property changes the name of the active worksheet ActiveSheet.Name = "mySheet" ' Index property displays the tab number of the sheet that you specified Worksheets("mySheet").Index ' Calculate method calculates the first worksheet Worksheets(1).Calculate ' this example Comments collection shows how many comments there are in 1st sheet Worksheets(1).Comments.Count ' this Cells property displays 65535, which denotes the number of rows in a worksheet Cells.Rows.Count ' the Cells property cycles through a range of cells using For Next loop, and substitute variables for the index numbers Dim Counter As Integer For Counter = 1 To 12 Worksheets(1).Cells(Counter, 2).Value = Counter Next Counter Cells(1, 2).Select ‘ this selects cell B1 ' this Columns property formats column 1 with Bold font Worksheets(1).Columns(1).Font.Bold = True ' this Rows property deletes row 1 Worksheets(1).Rows(1).Delete ' this Add method and Type property add two chart sheets to the active workbook, placing them after sheet two Sheets.Add Type:=xlChart, Count:=2, after:=Sheets(2) ' this Add method and Type property give the same result as above ActiveWorkbook.Sheets.Add Type:=xlChart, after:=Sheets(Sheets.Count - 2), Count:=2 ' Protect method protects Sheet1 in "MainWorksheetObjects" workbook with password 'william". Unprotect, the opposite Workbooks("MainWorksheetObjects").Worksheets(1).Protect Contents:=True, Password:="william" Workbooks("MainWorksheetObjects").Sheets(1).Unprotect Password:="william" ' this example Delete method deletes the 4th worksheet Worksheets("Sheet4").Delete ' these 2 methods to preview or print out the active worksheet Worksheets(1).PrintPreview Worksheets(1).PrintOut ' Move method let you move Sheet2 after Sheet3 in the active workbook Worksheets("Sheet2").Move after:=Worksheets("Sheet3") ' the Visible property hides Sheet3. set it to True will unhide the sheet Worksheets("Sheet3").Visible = False ' Select method selects a particular worksheet. It select Sheet2 Worksheets("Sheet2").Select ' SaveAs method saves the workbook under a different filename Worksheets("Sheet2").SaveAs ("C:\MyWorksheetObjectsFile") ' this Copy method example let you copy the first Sheet to a new workbook Worksheets(1).Copy You can download as a demo workbook from here
' Value property input values to the range A1:C4 Worksheets("Sheet1").Range("A1:C4").Value = "Mycells" ' Cells collection displays how many cell are within the specified range Worksheets("Sheet1").Range("A1:C4").Cells.Count ' Address property display different representations of the same cell A1 on Sheet1
Set Addr = Worksheets("Sheet1").Cells(1, 1)MsgBox Addr.Address() ' it displays $A$1 MsgBox Addr.Address(RowAbsolute:=False) ' it displays $A1 MsgBox Addr.Address(ReferenceStyle:=xlR1C1) ' it displays R1C1 'this Copy and PasteSpecial methods copy and paste a range of cells, from 1st to 2nd sheet Worksheets(1).Range("A1:C4").Copy Worksheets(2).Range("D1").PasteSpecial 'this does the same trick as above by skipping the PasteSpecial method Worksheets(1).Range("A1:C4").Copy Worksheets(2).Cells(1, 4) ' this method activates a range of cells to make into active cells Worksheets("Sheet1").Range("A1:C4").Activate ' Columns and Rows property display the number of columns & rows respectively Worksheets(1).Range("A1:E8").Columns.Count Worksheets(1).Range("A1:E8").Rows.Count ' Column & Row property return the 1st column number or the 1st row number within the range Worksheets(1).Range("B4:E8").Column Worksheets(1).Range("B4:E8").Row ' ColumnWidth and RowHeight properties sets the width of columns & height of rows Worksheets(1).Range("A1:E8").ColumnWidth = 6 Worksheets(1).Range("A1:E8").Rowheight = 14 ' replace method replaces a specified character found within the range with another one Worksheets(1).Range("A1:C4").Replace "My", "Testing" ' this property sets whether text will wrap within a cell (True) or stay on one line (False) Worksheets(1).Range("A1:C4").WrapText = True ' ClearContents method clears content of a range of cells, but does not clear the format or border Worksheets("Sheet1").Range("A1:C4").ClearContents ' Clear method clears everything - content, formats, borders Worksheets("Sheet2").Range("A1:C4").Clear ' the Find method looks for 1905 in formulas in cells after the active cell, without searching for its ' cell format. In fact you can skip all the optional parameters to just Cells.Find(What:=1905).Activate Cells.Find(What:="1905", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate ' UsedRange Property represents the used range on the active worksheet ActiveSheet.UsedRange.Select You can download as a demo workbook from here |
This site was created in Feb.2007 by William Tan |