0% found this document useful (0 votes)
73 views8 pages

VBA For Modelers (Chapter 2)

Capitulo 2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
73 views8 pages

VBA For Modelers (Chapter 2)

Capitulo 2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
10 2.1 2.2 The Excel Object Model Introduction This chapter introduces the Excel object model—the concept behind it and how it is implemented. Even if you have programmed in another language, this will probably be new material, even a new way of thinking, for you. However, with out understanding Excel objects, you will not be able to proceed very far with VBA for Excel. This chapter provides just enough information to get you started. Later chapters focus on many of the most important Excel objects and how they can be manipulated with VBA code. Objects, Properties, Methods, and Events Consider the many things you see in the everyday world. To name a few, there are cars, houses, computers, people, and so on. These are all examples of objects. For example, let’s focus on a car. A car has attributes, and there are things you can do to (or with) a car. Some of its attributes are its weight, its horsepower, its color, and its number of doors. Some of the things you can do to (or with) a car are drive it, park it, accelerate it, crash it, and sell it. In VBA, the attributes of an ‘object are called properties: the size property, the horsepower property, the color property, the number of doors property, and so on. In addition, each property has a value for any particular car. For example, a particular car might be white and it might have four doors. In contrast, the things you can do to (or with) an object are called methods: the drive method, the park method, the accelerate method, the crash method, the sell method, and so on. Methods can also have qualifiers, called arguments, that indicate /ow a method is performed. For exam ple, an argument of the crash method might be speed—how fast the car was going when it crashed. The following analogy to parts of speech is useful. Objects correspond to nouns, properties correspond to adjectives, methods correspond to verbs, and arguments of methods correspond to adverbs. You might want to keep this anal- ogy in mind as the discussion proceeds. Now let’s move from cars to Excel. Imagine all of the things—objects—you work with in Excel. Some of the most common are ranges, worksheets, charts, and workbooks. (A workbook is really just an Excel file.) Each of these is an object in the Excel object model. For example, consider the single-cell range BS. 23 The Excel Object Model 11 This cell is a Range object.’ Like a car, it has properties. It has a Value property: the value (either text or number) displayed in the cell. It has a HorizontalAlignment property: left-, center-, or right-aligned. It has a Formula property: the formula (if any) in the cell. These are just a few of the many properties of a range. ‘A Range object also has methods. For example, you can copy a range, so Copy is a method of a Range object. You can probably guess the argument of the Copy method: the Destination argument (the paste range). Another range method is the ClearContents method, which is equivalent to selecting the range and pressing the Delete key. It deletes the contents of the range, but it does not change the formatting. If you want to clear the formatting as well, there is also a Clear method. Neither the ClearContents method nor the Clear method has any arguments. Learning the various objects in Excel, along with their properties and meth- ods, is a lot like learning vocabulary in English—especially if English is not your native language. You learn a little at a time and generally broaden your vocabulary through practice and experience. Some objects, properties, and methods are natu- rally used most often, and you will learn quickly. Others you will never need, and you will probably remain unaware that they even exist. However, there are many times when you will need to use a particular object or one of its properties or methods that you have not yet learned. Fortunately, there is excellent online help available—a type of dictionary—for learning about objects, properties, and meth- ‘ods. It is called the Object Browser and is discussed in the next chapter. There is one other important feature of objects: events. Some Excel objects have events that they can respond to. A good example is the Workbook object and its Open event. This event happens—we say it fires—when the workbook is opened in Excel. In fact, you might not realize it, but the Windows world is full of events that fire constantly, Every time you click or double-click a button, press a key, move your mouse over some region, or perform a number of other actions, various events fire, Programmers have the option of responding to events by writ- ing event handlers. An event handler is a section of code that runs whenever the pciated event fires. In later chapters, particularly Chapter 11, you will lear how to write your own event handlers. For example, it is often usefull to write an event handler for the Open event of a Workbook object. Whenever the workbook is opened in Excel, the event handler then runs automatically. It could be used, for example, to ensure that the user sces a certain worksheet when the workbook opens Collections as Objects Continuing the car analogy, imagine that you enter a used car lot. Each car in the lot is a particular car object, but it also makes sense to consider the collection of all 2 From here on, “proper” ease, such as Range or Hoszontalignment, will be used for objects, properties, and methods. This is the convention used in VBA. Als, they appear in this book ina different font. 12 Chapter 2 24 cars in the lot as an object. This is called a Collection object. Clearly, the collection of cars is not conceptually the same as an individual car. Rather, it is an object that includes all of the individual car objects. Collection objects also have properties and methods, but they are not the same as the properties and methods of the objects they contain, Generally, there are many fewer properties and methods for collections. The two most common are the Count property and the Add method. The Count property indicates the number of objects in the collection (the number of cars in the lot). ‘The Add method adds a new object to a collection (a new car joins the lot). It is easy to spot collections and the objects they contain in the Excel object model. Collection objects are plural, whereas a typical object contained in a collec- tion is singular. A good example involves worksheets in a given workbook. The Worksheets collection (note the plural) is the collection of all worksheets in the workbook. Any one of these worksheets is a Worksheet object (note the singular). Again, these must be treated differently. You can count worksheets in the Work- sheets collection, or you can add another worksheet to the collection. In contrast, typical properties of a Worksheet object are its Name (the name on the sheet tab) and Visible (True or False) properties, and a typical method of a Worksheet object is the Delete method. (Note that this Delete method reduces the Count of the Worksheets collection by onc.) ‘The main exception to this plural/singular characterization is the Range object. There is no “Ranges” collection object. A Range object cannot really be considered singular or plural; it is essentially some of each. A Range object can be a single cell, a rectangular range, a union of several rectangular ranges, an entire column, or an entire row. Range objects are probably the most difficult to master in all of their varied forms. This is unfortunate because they are the most frequently used objects in Excel. Think of your own experience in Excel, and you will realize that you are almost always doing something with ranges. An entire chapter, Chapter 6, is devoted to Range objects so that you can master some of the techniques for manipulating these important objects. The Hierarchy of Objects Returning one last time to cars, what is the status of a car’s hood, a car’s trunk, or a car’s set of wheels? These are also objects, with their own properties and methods. In fact, the set of wheels is a collection object that contains individual wheel objects. The point, however, is that there is a natural hierarchy, as illus- trated in Figure 2.1, The Cars collection is at the top of the hierarchy. It contains a set of individual cars. The notation Cars (Car) indicates that the collection object is called Cars and that each member of this collection is a Gar object. Each car “contains” a number of objects: a Wheels collection of individual Wheel objects, a Trunk object, a Hood object, and others not shown. Each of these can have its own properties and methods. Also, some can contain objects farther down the hierarchy. For example, the figure indicates that an object down the hierarchy from Hood is the HoodOmament object. Note that each of the rectangles in this ‘The Excel Object Model 18 Figure 2.1. Object Model for Cars 25 ‘Wheels(Wheel) [Trunk Hood Sire figure represents an object, Each object has properties and methods that could be shown emanating from its rectangle, but this would greatly complicate the figure. The same situation occurs in Excel. The full diagram of the Excel object model appears in Figure 2.2. (This is the Excel 2003 version; versions for Excel 2007 or later are only slightly different.’) This figure shows how all objects, including collec: tion objects, are arranged in a hierarchy. At the top of the hierarchy is the Application object. This refers to Excel itself One object (of several) one step down from Appi cation is the Workbooks collection, the collection of all open Workbook objects. This diagram is admittedly quite complex. All you need to realize at this point is that Excel has a very rich object model—a lot of objects; fortunately, you will need only a relatively small subset of this object model for most of your applications. This rela: tively small subset is the topic of later chapters. Object Models in General Although the Excel object model is used in this book, you should now have some understanding of what it would take to use VBA for other applications such as Word, Access, or even non-Microsoft products. In short, you would need to learn its object model. You can think of each application “plugging in” its object model to the underlying VB language. Indeed, third-party software developers who want to license VBA from Microsoft need to create an object model appro: priate for their application. Programmers can then use VBA to manipulate the objects in this model. This is a powerfull idea, and it is the reason why VBA is the programming language of choice for so many developers—regardless of whether they are working in Excel or any other application. Figures 2.3 and 2.4 illustrate two other object models. (Again, these are the Office 2003 versions.) The object model in Figure 2.3 is for Word. A few of these objects are probably familiar, such as Sentence, Paragraph, and Footnote. If you For example, if you perform a Web search for “Excel 2013 object model diagram,” you will see a number of such diagrams 14 Chapter 2 Figure 2.2 Excel Object Model The Excel Object Model 15 Figure 2.3. Word Object Model zation ] {nai ] U geecron ] (Selection ] +akataptions 1 | floskmank ] Shading j Hautetorrect ] HBorders r (ShapeRange =i) (RutoCorrectEntries: = Heels ] (SmartTags } ietteterbxceptions ———] + (iaractre ] ables j (HangulAndAiphabetfxceptions ) [{fotumns: ] (Words ] (DierCorrectonstxceptions —] + {Comments 1 alNede 1 {TwatnilCapabceptons —] {Document ] anodes ] Hirowser 1 + Eaitors 1 ‘SmareTagHecognizere ] HEaptiontabels: ] HndnoteOptions: ] [SmartTagTypes. ] y Bialoae J ets J Sze J HDictionaries: ] | Trelis ] [System ] | Bocimente 1 or | rasan j Hemailoptions: 1 Heeat_ ] [Tasks ] aie 1 | Fosinotedptione 1 mate ] Sie 1 Hfeatnotes > (ratoToatrien 1 -{Fletonverers 1 | mets ] iatrempiates 1 “onions 1 frames | Hienoiates 1 THanjatonversionbitionarcs] _|fleaderFoter 1 Hos 1 = | eee srs —— Keypindings Legend eyssoundro il peee en fanauaoes object en {(atGaenes oe ET) {Customtabels | ed [Sections a) were leaming VBA for Word, you would need to learn the most common elements Of this object model. Figure 2.4 shows part (about 40%) of the object model for Microsoft Office as a whole. You might wonder why Office has a separate object ‘model from Excel or Word. The reason is that Office is an integrated suite, where all of its programs—Excel, Word, PowerPoint, Outlook, and the rest—share a number of features, For example, they all have menus and toolbars, referred to collectively as the CommandBars collection in the object model. Therefore, if you 16 Chapter 2 Figure 2.4 Part of Office Object Model [AnswerWizard U [AnswerWizardFiles [Assistant Ugatioon [BalloonCheckboxes Upatfoontheckbox [Balloontabels iBalloonLabel G (COMAddIns Lgoranaatn ymmandBarButton -e (CommandBar [ commandBarcontrote (CommandBarControl [CommandBarCombobox (CommandBar U [CommandBarControls U (CommandBarControl [CommandBarPopup = [CommandBarControls U (CommandBarControl mmandBars. (Co Lae U {CommandBarControls U {CommandBarControl 26 The Excel Object Model 17 ‘want to use VBA to manipulate toolbars or menus in Excel, as many programmers do, you have to learn part of the Office object model. But then this same knowl cdge would enable you to manipulate menus and toolbars in Word, PowerPoint, and the others, (Actually, menus and toolbars were replaced for the most part by ribbons in Excel 2007 and later versions, but the CommandBar object is still present. This topic is discussed in Chapter 16.) The Excel object mode! continues to evolve as new versions of Excel are released. Sometimes new objects, properties, or methods are added. Other times, some are dropped from the official object mode! but still continue to work, for backward compatibility. Occasionally, some are dropped completely, so that pro- grams written in an earlier version no longer work. Fortunately, these are the rare exceptions. If you are working in Excel 2007 or later versions and are interested in seeing the types of changes that have been made, open the Visual Basic Editor (Alt+F11 from Excel), press the Fl key for help, and search for “object model changes.” Although the list is fairly long, not much in terms of VBA code has changed since this book was originally written for Excel 2003. Summary This chapter has introduced the concept of an object model, and it has briefly introduced the Excel object model that is the focus of the rest of the book. If you have never programmed in an object-oriented environment, you can look forward to a whole new experience, However, the more you do it, the more nat- tural it becomes, It is certainly the dominant theme in today’s: programming world, so if you want to be part of this world, you have to start thinking in terms of objects. You will get plenty of chances to do so throughout the book.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy