I’ve got to confess something to you:
I cover the topic of VBA objects extensively in Power Spreadsheets, including here and here. However, when working in Visual Basic for Applications, you can’t really do anything meaningful by knowing only what I explain in those Excel tutorials.
Let me explain what I mean:
There is no doubt that the concept of objects is central to VBA. After all, VBA is loosely based on the concept of object-oriented programming.
However, as explained by John Walkenbach in Excel VBA Programming for Dummies:
(…) you can’t do anything useful by simply referring to an object (…).
In order to actually start “doing something” with an object, you need to understand at least 1 of the following topics:
- Object properties.
- Object methods.
To be more precise:
In order to become great in VBA, you actually need to understand and master both properties and methods. This Excel tutorial covers 1 of these topics:
Object properties.
More particularly, in this blog post you’ll read about the following topics:
If you’re interested in reading about object methods, please click here.
Let’s start learning about the topic of VBA object properties by remembering what they actually are:
What Are VBA Object Properties
As I explain in this Excel VBA tutorial, properties are the named attributes of an object or, in other words, what you can use to describe an object, such as its:
- Attributes.
- Characteristics.
- Qualities.
In Excel 2013 VBA and Macros, Excel authorities Bill Jelen and Tracy Syrstad liken properties to adjectives. In the regular English language, adjectives describe or clarify a noun.
In the context of Visual Basic for Applications, objects are the equivalent of nouns. Therefore, within VBA, properties (adjectives) describe objects (nouns).
The above comments apply to object collections (which are objects themselves) as well. In other words, collections also have properties that describe them.
As mentioned in Mastering VBA for Microsoft Office 2013, every object within Visual Basic for Applications has properties. This makes sense, after all, properties determine things such as:
- How the object looks like.
- How the object behaves like.
- Whether you can or can’t see the object.
In fact, most objects have several properties, with each property determining a different characteristic of the object.
Richard Mansfield explains, in Mastering VBA for Microsoft Office 2013, how objects of the same type have the same set of properties. However, each of the individual objects stores their own individual values for each of those properties. In other words:
(…) each object is independent of the other objects.
As explained in Excel VBA Programming for Dummies, Excel 2013 Power Programming with VBA and Excel 2013 VBA and Macros, VBA allows you to do the following 2 things with the properties of an object:
Object Property Use #1: Read Them
This means, in other words, fetch or return the current settings of an object property.
As explained in the Excel 2013 Bible, you’d generally examine the current property of an object for purposes of taking a particular course of action depending on the value of that property.
However, properties can also be used to return objects. In fact, most VBA objects are actually accessed through the use of properties. For example, the macro samples that are used below in this Excel VBA tutorial use the Range.Interior property for these purposes.
Object Property Use #2: Modify Them
This means, more precisely, change the current setting of that property and set it to a certain value.
Based on the 2 uses above, you can classify VBA object properties in read/write, read-only or write-only properties. Let’s see what each of these means:
Read And Write VBA Object Properties
As mentioned by Richard Mansfield in Mastering VBA for Microsoft Office 2013, “many properties are read/write“. This means that you can carry out both of these actions (read or modify) in connection with such properties.
However, as you’ll see below, not all properties are like this. There are both read-only and write-only properties. As implied by the description, you can only:
- Read (but not set) read-only properties.
- Set (but not read) write-only properties.
I show you step-by-step examples of how to do both of this below.
How Do You Work With A VBA Object Property
In order to understand the syntax you should use in order to work with a VBA object property, let’s use 2 practical examples:
- Example #1: We take a look at an example where the VBA code changes the current setting of a property.
- Example #2: We see an example of a macro that reads and displays the current settings of that same property.
In both cases, I’ll provide additional information about the particular case. However, the general rule for referring to a VBA object property is clearly explained by John Walkenbach in the Excel 2013 Bible:
You refer to a property in your VBA code by placing a period (a dot) and the property name after the object’s name.
In other words, you generally:
- Refer to the object and then to the property, as mentioned in Excel Macros for Dummies.
- Separate the object from the property with a period (.).
As explained below, whenever you’re setting the value of a particular object property, you generally include an additional element: the property value you’re setting. However, even in such cases, you continue to use the basic syntax described above.
Let’s go to the examples and see how this syntax looks in practice:
VBA Object Property Syntax Case #1: Setting A Property Value
The following macro (called Find_Format_Formulas) finds, selects and formats all formulas in the active Excel worksheet. More precisely, this macro highlights in light yellow any cell that contains a formula.
This Excel VBA Properties Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Find_Format_Formulas macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Let’s take a look at the practical results of executing the Find_Format_Formulas macro:
I’ve typed the following (random) formula using the SUM function. Notice how none of the cells that appear in the screenshot is highlighted.
The following screenshot shows the same cells after the Find_Format_Formulas macro is executed. Notice how, now, the cell with the formula is highlighted in light yellow.
Described in plain English, the macro has changed the fill color of the cell.
Let’s describe what is happening in a slightly more structured manner to see what Visual Basic for Applications has done:
- The cell itself is an object.
- The fill color is an attribute that you can use to describe the cell. In other words, the fill color is a VBA object property.
- The Find_Format_Formulas macro has modified the value of the fill color property.
Let’s go back to the VBA code of the Find_Format_Formulas and focus on the statement that determines the new value of the fill color VBA property. This statement is:
my_Range.Interior.ColorIndex = 36
The following screenshot shows the location of this statement within the Find_Format_Formulas Sub procedure:
Let’s take a close look at each of the elements in this statement to understand its structure:
Element #1: Object (my_Range.Interior)
my_Range is an object variable. Object variables serve as a substitute for actual objects.
In this example, my_Range is a Range object.
The Range.Interior property is used for purposes of returning the interior of the relevant range. In the case of this example, this is the interior of the cells that contain formulas. This, in turn, is an Interior object.
In other words, this first element represents the interior of the cells that contain formulas. This the object whose attribute (color, in the example above) changes. This sentence can be reworded in VBA terms as follows:
my_Range.Interior represents the object whose property (fill color) is modified.
Element #2: Dot (.) Operator
As a general rule, Visual Basic for Applications uses the dot (.) operator to connect and separate the various items you can work with.
You can think of the dot (.) operator as the rough equivalent to the word “of” in plain English. The following are the basics of the dot (.) notation:
- It’s hierarchical and usually begins with an object.
As a consequence of the above, the hierarchy of VBA objects in Excel is of particular importance.
- Once you’ve identified the object, you include a dot (.) to separate the object from the relevant property or method.
Notice how, in the example above, we’ve used additional dots when identifying the object (my_Range.Interior). This happens because, depending on matters such as how you craft your object references and which particular object you’re working with, you may have to use additional dots when identifying the object.
- After the dot, you type the relevant property or method.
In the case of this Excel tutorial, you already know that we’re working with properties (not methods). Therefore, what the next element in the statement is shouldn’t be a surprise to you:
Element #3: Property (ColorIndex)
You can use the ColorIndex property to either return or set the color of the relevant object (usually a border, font or interior).
In the example above, we’re modifying the actual property (not reading it). Therefore, let’s take a look at the last element of the statement to see how the property value is set…
Element #4: Property Value (= 36)
In order to be able to modify the value of a property, you must work with arguments. In Excel 2013 Power Programming with VBA, John Walkenbach explains that not all properties use arguments. However, some (such as ColorIndex) do.
In the cases where a property uses arguments, the main purpose of such argument is to specify the value of the property. According to Walkenbach, property arguments is an issue that often “leads to confusion among new VBA programmers”.
However, the basic syntax for specifying arguments for VBA object properties isn’t particularly complicated. In fact, the general rule is as simple as shown above:
You use an equal sign (=) to separate the property name from the property value.
As mentioned in Excel 2013 VBA and Macros and Microsoft Excel 2013 In Depth, the equal sign (=) is a good indication that you’re looking at a property value. If you see a colon (:) before the equal sign (:=), you’re likely looking at a method.
In other words, to set the value of a property, you:
- Refer to the property.
- Place an equal sign (=) after the VBA object property name.
- Set the value of the object property.
Therefore, in the statement above, the ColorIndex property is used to set the color of the Interior object identified in the first part of the statement (the interior of the cells that contain formulas) to color 36 of the color palette. Color 36 is the light yellow that appears in the screenshot above.
In other words, the basic syntax you must follow in order to be able to set the value of a VBA property (as partially explained above) is:
Object.Property = Property_Value
The first part (Object.Property) is the general syntax that I describe above and that you use when reading a property value. In other words, this is the basic structure you need to know.
When setting the value of an object property, you only need to add the last elements (= Property_Value): an equal sign and the property value.
You won’t be able to modify absolutely all object properties using Visual Basic for Applications by using the syntax described above. There are some object properties that are read-only. For example:
- In the Excel 2013 Bible, John Walkenbach lists the Row and Column properties of a single-cell Range object.
- In Excel Macros for Dummies, Michael Alexander mentions the “Text property of cell”.
The consequence of a property being read-only, as you can probably imagine, is that:
- You can read the object property…
- But you can’t modify it.
Let’s turn, then, to the second case of property use:
VBA Object Property Syntax Case #2: Reading A Property Value
Let’s go back to the Excel workbook in which the sample Find_Format_Formulas macro was run:
The following screenshot shows the only worksheet of that workbook. Notice how there’s only 1 cell (B5) whose fill has been set to light yellow by the Find_Format_Formulas macro:
The following Sub procedure (named Display_ColorIndex) shows a message box displaying the value of the ColorIndex property for cell B5 of the worksheet named VBA Object Properties. The basic structure of this piece of VBA code is suggested by John Walkenbach in both Excel VBA Programming for Dummies and Excel 2013 Power Programming with VBA.
The following is the message box that Excel displays when the Display_ColorIndex macro is executed:
The value displayed (36) makes sense. Cell B5 of the worksheet named VBA Object Properties is the only cell with a light yellow fill. We already know from the previous macro Find_Format_Formulas, that this light yellow is color 36 in the color palette for the ColorIndex property.
Let’s focus, once again, on the most relevant section of the macro. The following image shows the part of the statement that is responsible for reading the value of the ColorIndex property of cell B5’s interior:
This probably looks familiar.
You’ll notice that this is materially the same structure that we saw before when looking at how to modify the settings of an object property. Let’s take a look at the 3 elements of this statement to make it even clearer:
Element #1: Object (Worksheets(“VBA Object Properties”).Range(“B5”).Interior)
This structure is substantially similar to that I describe above. In other words:
- The first part (Worksheets(“VBA Object Properties”).Range(“B5”)) of this section follows the general way of crafting references to Excel’s Range object.
- The Range.Interior property is used for purposes of returning an Interior object. In this case, this object is the interior of cell B5 in the worksheet called VBA Object Properties.
There is, however, a substantial difference: the Display_ColorIndex macro has no object variables whereas the Find_Format_Formulas macro in the previous section does.
Element #2: Dot (.) Operator
The dot (.) operator serves exactly the same purpose as in the Find_Format_Formulas macro above. In other words, it’s used to connect and separate element #1 above (the object) with element #3 below (the property).
Element #3: Property (ColorIndex)
The ColorIndex property can be used to set the color of an object (such as the interior of a cell). This is what the property does in the Find_Format_Formulas above.
However, ColorIndex can also be used to return the color of an object. This is the way in which the property is used in the Display_ColorIndex macro under analysis.
This analysis confirms what we’d seen above. More precisely, it confirms that the basic syntax that you can use to refer to Excel VBA properties is the same regardless of whether you are changing or examining the setting of that particular property. Just as a reminder, this basic syntax is:
Object.Property
I suggest you exercise care when creating references to objects and properties. Even though the basic syntax isn’t complicated, is important to make sure that you’re correctly identifying the relevant collections and the appropriate object from within the collection, as well as correctly using properties to refer to an object. If you fail to do this properly, you’ll usually receive an error message when trying to execute the macro.
For example, let’s assume that, instead of typing “VBA Object Properties” to identify the object from within the Worksheets collection I want to work with, I type the default “Sheet1”. In other words, the VBA code of the Display_ColorIndex macro looks as follows:
Sheet1 doesn’t exist within the example workbook that accompanies this Excel VBA Properties tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Therefore, when I try to execute the Display_ColorIndex macro, Visual Basic for Applications returns the following error:
Obtaining an error in such a case makes sense. After all, as John Walkenbach explains in Excel VBA Programming for Dummies:
VBA just follows instructions, and it can’t work with a sheet that doesn’t exist.
Finally, remember that there are some instances in which you’ll not be able to read an object’s properties. In those cases, the property is deemed to be write-only.
In Excel 2013 Power Programming with VBA, John Walkenbach explains how this is the case, for example, in connection with the Value and Formula properties of certain cell Range objects. More precisely, you can only read the Value and Formula properties for a single-cell objects. This limitation (however) only applies to reading the property. You can actually modify the Value and Formula properties for multi-cell Range objects.
The consequences of a property being write-only are the following:
- You can’t read the object property…
- But you can modify it.
This is exactly the opposite of what happens in the case of read-only properties, which are described above.
Before we move on to the next topic, let’s take a quick look at 2 final clarifications regarding the syntax you should use when working with VBA object properties:
Default Object Properties And Properties That Return Values
Most VBA objects have a particular property that is their default. Therefore, theoretically, you can omit certain parts of the code. In other words, you can simply make reference to the VBA object, without including the property after it.
However, as mentioned in Excel 2013 Power Programming with VBA, including the VBA property explicitly in your code is a good programming practice. This is the case even if the property you’re making reference to is the default property.
Finally, note that Excel 2013 Power Programming also explains that in the case of properties that return a value, you must place parentheses around the arguments. This is an exception to the rules that I explain in the sections above.
Now that you know how to refer to and work with Excel VBA object properties, you may wonder…
How Do You Know Which Properties Are Available For A Particular VBA Object
According to John Walkenbach, there are:
(…) literally thousands of properties and methods available.
Fortunately, you won’t need to work with most of them. Most likely, you’ll end up working with a relatively small portion of the available VBA object properties again and again.
Additionally, even though each VBA object has its own properties, some properties are common to several objects. The following are some of the examples of common VBA properties. These examples are further explained in Excel VBA Programming for Dummies and Mastering VBA for Microsoft Office 2013:
- The Visible property.
- The Name property.
- The Saved property.
However, since you’re likely to (from time to time) need some help to find out the properties that are available for a particular VBA object, let’s take a look at 3 ways in which you can get this information.
And in any case, remember that the macro recorder can help you identify/see what you need“.
Method #1: Use The Object Browser
As implied by its name, the Object Browser within the Visual Basic Editor allows you to browse through VBA objects. Perhaps more importantly, it shows you the properties, methods and events of each of those objects.
You can access the Object Browser in any of the following ways:
- Click on the Object Browser button in the Standard toolbar.
- Go to the View menu and select “Object Browser”.
- Use the keyboard shortcut “F2”.
Once the Visual Basic Editor is displaying the Object Browser, you can have the VBE display all the relevant information about a particular object by following these 2 easy steps:
Step #1: Select The Excel Library
On the top left-hand corner of the Object Browser, you’ll notice a drop-down list that says “<All Libraries>”.
Click on this drop-down list and select “Excel”.
Step #2: Select The Appropriate Object Class
Once you’ve selected the Excel library, the Object Browser displays all the Excel objects in the left side of the screen. Simply search for the one you want and click on it.
Once you’ve clicked on a particular object, the Object Browser lists all the properties and methods available for that object on the right side of the screen.
For example, the following image shows how the Object Browser looks like when I click on “Interior”. Notice how the ColorIndex property (which is used in both sample macros within this Excel tutorial) appears on the right side.
Method #2: Use The Microsoft Developer Network
The Microsoft Dev Center contains an extensive amount of information about VBA objects and properties. The easiest way to find information about a particular object using this tool is by following these 3 simple steps:
Step #1: Enter An Object In The Visual Basic Editor
This step is self-explanatory. Simply type the name of the object you wish to find more information about.
Let’s assume that we want to find more information about the Range object while working in the sample Display_ColorIndex macro. Therefore, the VBA code looks as follows:
Step #2: Place The Cursor Within The Object Name
This step doesn’t require much further explanation.
The following screenshot shows how this looks like when the relevant object is Range and we’re working with the Display_ColorIndex macro:
Step #3: Press The F1 Key
The F1 key is the keyboard shortcut to open the help system. You can find a comprehensive list of keyboard shortcuts in this blog post.
If the Visual Basic Editor finds that there are several possible matches for the keyword you’ve selected, it asks you to select a topic. This is what happens in the case of Range.
If there’s no ambiguity (it’s clear which word you want to get information about), or once you’ve selected a topic in the Context Help dialog (as in the case above), you’re led to the relevant page within the Microsoft Developer Network.
For example, in the case above, once I choose the first option (“Range(object)”) and press the Help button on the upper right corner of the Context Help dialog, the Microsoft Developer Network displays the page that corresponds to this object. You can have the Microsoft Developer Network display all the properties that correspond to the Range object by clicking on, or expanding the menu, “Properties” on the left sidebar.
Method #3: Make The Visual Basic Editor Display A List Of Properties
Probably the easiest way of getting an idea of the properties of a particular object is by getting help from the Visual Basic Editor.
The VBE displays a list with all the items (such as properties and methods) that can be associated with a particular object once you’ve typed the dot (.) that follows that VBA object.
Let’s take a look at an example by going back to the VBA code of the Find_Format_Formulas macro. The following screenshot shows how the Visual Basic Editor displays a list of properties and methods immediately after I type the dot (.) that follows “my_Range.Interior”.
In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled. I explain how to do this here.
This helps you get an idea of what are the properties and methods (in the example above, the VBE shows only properties) that you have available in a particular situation.
Conclusion
The concept of object properties is central to Visual Basic for Applications. Therefore, if you plan on working with VBA, you’ll spend a great deal of time dealing with object properties.
Despite being a relatively basic concept, the topic of properties can be quite overwhelming. As mentioned above, there are thousands of object properties available throughout Visual Basic for Applications.
The good news is that you don’t have to know absolutely all VBA object properties by heart in order to be able to do great work with Visual Basic for Applications. As long as you have a good understanding of the following 2 basic topics, you have a good base to start moving forward:
- How to refer to and work with object properties.
- How to search for and find the object properties you need.
Both of these matters were covered in this Excel tutorial.
Books Referenced In This Excel Tutorial
- Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Jelen, Bill (2013). Excel 2013 In Depth. United States of America: Que Publishing.
- Jelen, Bill and Syrstad, Tracy (2013). Excel 2013 VBA and Macros. United States of America: Pearson Education, Inc.
- Mansfield, Richard (2013). Mastering VBA for Microsoft Office 2013. Indianapolis, IN: John Wiley & Sons Inc.
- Walkenbach, John (2013). Excel 2013 Bible. Indianapolis, IN: John Wiley & Sons Inc.
- Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.
Содержание
- Общие сведения об объектах, методах, свойствах и событиях
- Объекты и коллекции
- Возврат объектов
- Методы
- Свойства
- События
- См. также
- Поддержка и обратная связь
- Understanding objects, methods, properties, and events
- Objects and collections
- Returning objects
- Methods
- Properties
- Events
- See also
- Support and feedback
- VBA Objects Properties and Methods in Excel
- VBA Reference
- 120+ Project Management Templates
- What are Objects?
- What are Properties?
- What are Methods?
- VBA Objects Properties and Methods in Excel – Object Browser?
- Excel VBA
- Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods
Общие сведения об объектах, методах, свойствах и событиях
Объекты и коллекции
Объект представляет элемент приложения, такой как лист, ячейка, диаграмма, форма или отчет. В коде Visual Basic необходимо идентифицировать объект, прежде чем можно будет применить один из методов объекта или изменить значение одного из его свойств.
Коллекция — это объект, который содержит несколько других объектов обычно, но не всегда, одного типа. Например, в Microsoft Excel объект Workbooks содержит все открытые объекты Workbook. В Visual Basic коллекция Forms содержит все объекты Form в приложении.
Элементы в коллекции могут идентифицироваться по номеру или по имени. Например, в указанной ниже процедуре первый открытый объект Workbook идентифицируется по номеру.
В приведенной ниже процедуре используется имя, указанное в виде строки, для идентификации объекта Form.
Можно также обрабатывать всю коллекцию объектов, если объекты совместно используют общие методы. Например, следующая процедура закрывает все открытые формы.
Возврат объектов
Каждое приложение имеет способ возврата содержащихся в нем объектов. Однако они отличаются, поэтому необходимо ознакомиться со справочным разделом по объектам или коллекциям, используемым в приложении, чтобы узнать, как возвратить объект.
Методы
Метод — это действие, которое может выполняться объектом. Например, Add — это метод объекта ComboBox, так как им добавляется новая запись в поле со списком.
В следующей процедуре метод Add используется для добавления нового элемента в ComboBox.
Свойства
Свойство — это атрибут объекта, которой определяется одно из характеристик объекта, такая как размер, цвет, местоположение экрана или характер поведения объекта, например включен ли он и является ли видимым. Чтобы изменить характеристики объекта, изменяют значения его свойств.
Чтобы установить значение свойства, введите после ссылки на объект точку, имя свойства, знак равенства (=) и новое значение свойства. Например, указанная ниже процедура изменяет заголовок формы Visual Basic путем установки свойства Caption.
Некоторые свойства невозможно установить. В справочном разделе по каждому свойству указывается, можно ли установить это свойство (чтение-запись), только прочитать свойство (только чтение) или только записать свойство (только запись).
Сведения об объекте можно получить путем возврата значения одного из его свойств. В приведенной ниже процедуре используется окно сообщения для демонстрации заголовка, отображаемого в верхней части активной формы.
События
Событие — это действие, распознаваемое объектом, например щелчок мыши или нажатие клавиши, для которого можно написать код реагирования. События могут возникать в результате действий пользователя или кода программы либо вызываться системой.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Understanding objects, methods, properties, and events
Objects and collections
An object represents an element of an application, such as a worksheet, a cell, a chart, a form, or a report. In Visual Basic code, you must identify an object before you can apply one of the object’s methods or change the value of one of its properties.
A collection is an object that contains several other objects, usually, but not always, of the same type. In Microsoft Excel, for example, the Workbooks object contains all the open Workbook objects. In Visual Basic, the Forms collection contains all the Form objects in an application.
Items in a collection can be identified by number or by name. For example, the following procedure identifies the first open Workbook object.
The following procedure uses a name specified as a string to identify a Form object.
You can also manipulate an entire collection of objects if the objects share common methods. For example, the following procedure closes all open forms.
Returning objects
Every application has a way to return the objects it contains. However, they are not all the same, so you must refer to the Help topic for the object or collection that you are using in the application to see how to return the object.
Methods
A method is an action that an object can perform. For example, Add is a method of the ComboBox object, because it adds a new entry to a combo box.
The following procedure uses the Add method to add a new item to a ComboBox.
Properties
A property is an attribute of an object that defines one of the object’s characteristics, such as size, color, or screen location, or an aspect of its behavior, such as whether it is enabled or visible. To change the characteristics of an object, you change the values of its properties.
To set the value of a property, follow the reference to an object with a period, the property name, an equal sign (=), and the new property value. For example, the following procedure changes the caption of a Visual Basic form by setting the Caption property.
You can’t set some properties. The Help topic for each property indicates whether you can set that property (read-write), only read the property (read-only), or only write the property (write-only).
You can retrieve information about an object by returning the value of one of its properties. The following procedure uses a message box to display the title that appears at the top of the currently active form.
Events
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be triggered by the system.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
VBA Objects Properties and Methods in Excel
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Understanding VBA Objects Properties and Methods in Excel is important, most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.
In this Section:
What are Objects?
Most of the programming languages today are Object Based Or Object Oriented Programming Languages. Although Excel VBA is not a truly object oriented programming language, it does deal with objects.
VBA object is something like a thing that has certain functions, properties, and can contain data or child objects.
In real world everything is an object. For example, House is an Object, Windows and Doors,etc… are child objects of the House. And House is having some characteristics or properties such as Color, Height, Number of Floors,etc. and it also have some Events, such as Door Open, Door Close, etc….
Similarly, An Excel Worksheet is an object, and a Range or Cells in a worksheet are child objects of worksheet, Worksheet contains several Properties, Methods and Events.
You can go to the code window to view the VBA objects, the upper left drop-down list of the code window contains the list of objects and the right side drop-down list contains the associated objects.
What are Properties?
Properties are the characteristics of an Objects which can be measured and quantified, in the above example House is having properties like Width, Height, Color, etc…
Similarly, Excel Objects are having several properties which can be measured and quantified.
For example, a Range Objects is having Properties like Value,Font.ColorIndex, Interior.ColorIndex,etc…
What are Methods?
Methods are the actions that can be performed by an an Objects or on an Object. In the above Hose example, paintaing is a Method, building a new room is a method.
Similarly, if you want to select a range, you need Select method. If you want to copy a range from one worksheet to another worksheet you need Copy method to do it.
The following example Copies the data from Range A1 to B5.
VBA Objects Properties and Methods in Excel – Object Browser?
Object browser is a very helpful tool available in VBA, which helps you to veiw all available Objects in the Excel VBA. Click on the objects browser in the code window to view all the available Excel VBA objects and its associated Properties and Methods.
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Источник
Excel VBA
Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods
User Rating: 4 / 5
Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods
Contents:
An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object, a Method is an action performed by an object. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. An object is a thing which contains data and has properties and methods. To manipulate an Object you will Set its Properties and Call its Methods.
Visual Basic is not truly an Object-Orientated Programming (OOP) Language
Visual Basic (Visual Basic 6) is not truly an Object-Orientated Programming (OOP) Language whereas its successor Visual Basic.NET (part of the .NET platform) is a full-fledged Object Oriented programming language meeting the criteria of encapsulation, inheritance and polymorphism, where everything in Visual Basic.NET can be treated as an object. Visual Basic has many (but not all) elements of an Object-Orientated Programming (OOP) language. VBA deals with objects but is not truly an Object-Orientated Programming language.
VBA Objects
An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object (like name, color, size) or define an object’s behaviour (viz. if visible or enabled). An object’s data or information can be accessed with properties (viz. Value property, Name property). A Method is an action performed by an object. Calling a Method will execute a vba code which will cause the object to perform an action. You can associate objects with nouns, properties with adjectives and methods with verbs. An object could be a house, car, table or pen. Properties of a car include its color or size, which describe it. A car can perform actions of moving, accelerating or turning which are its methods. Examples of objects in Excel are workbook, worksheet, range, command button, font, etc. A Range object has «Value» as one of its properties and «Select» as one of its methods. Similarly a worksheet has, among others, a «Name» property, a «Delete» method, and a «Copy» method having arguments which contain information in respect of the worksheet to be copied.
Objects also have event procedures attached to them. Events are actions performed, or occurrences, which trigger a VBA code or macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. Excel provided built-in event procedure — an Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». In the Worksheet Change event procedure, the Worksheet object is associated with the Change event, which means that with the worksheet change event, a sub-procedure containing customized code runs automatically when you change the contents of a worksheet cell. Custom Events — you can also define your own events in custom classes (class modules), and create event procedures that run when those events occur.
A Collection Object in vba refers to a group of related items, as a single object. Many objects are present both in single form as well as in multiples. For example: (i) Workbook & Workbooks — all open Workbook objects in Excel are referred to as the Workbooks collection; (ii) Worksheet & Worksheets — A Worksheets Collection object refers to all Worksheets contained in a workbook. All elements (items) of a collection share the same properties and methods, though they do not need to be of the same data type. You can either create your own collection using the vba Collection class or use the Excel VBA built-in collections such as Worksheets (the Worksheets Collection Object includes all Worksheets in a workbook). With a Collection Object you can work with all objects (which are its elements) as a group as against working with a single object. The basic ways of working with elements of a collection include: adding an element using the Add method, removing an element using the Remove method, determining the number of elements contained in a collection using the Count property, accessing a specific element using the Item property, enumerate each element of a collection using the For Each. Next Statement, and so on.
The Excel Object Model
All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. When you use vba in an Office Application, say PowerPoint, a reference to the PowerPoint Object Library is set by default. When you Automate to work with PowerPoint objects from another application, say Excel, you can add a reference to the PowerPoint object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using PowerPoint’s predefined constants — the PowerPoint objects, properties, and methods will appear in the Object Browser and the syntax will be checked at compile time.
The Object Model of the Application (Excel) refers to and contains its programming objects which are related to each other in a hierarchy. The entire Excel application is represented by the Application Object which is at the top of the Excel object hierarchy and moving down you can access the objects from Application to Workbook to Worksheet to Range (Cells) and further on, by connecting the objects with a period (dot). Excel objects are accessed through ‘parent’ objects — Worksheet is the parent of the Range Object, and the Workbook is the parent of the Worksheet object, and the Application object is the parent of the Workbook object.
Example — Start at the top of the hierarchy with the Application object, then move down to the workbook, worksheet, range and font objects, as follows:
The Excel Object Model hierarchy — the most used objects:
The Application Object refers to the host application of Excel, and the entire Excel application is represented by it. The Workbook Object, appears next below the Application Object in Excel object hierarchy, and represents a single workbook within the Excel application. A workbook is also referred to as an Excel file. The Workbooks Collection Object includes all currently open Workbooks in Excel. The Worksheet Object, appears next below the Workbook Object in Excel object hierarchy, and represents a single worksheet within the workbook. The Worksheets Collection Object includes all Worksheets in a workbook. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells (when the Range is a union of multiple blocks of cells it is referred as a non-contiguous range of cells). The Range object is usually used maximum within the Excel application.
The Application object is the Default Object, Excel assumes it even when it is not specified. The Application qualifier is mostly not required to be used in vba code, because the default application is Excel itself, unless you want to refer to other outside applications (like Microsoft Word or Access) in your code or you want to refer to Excel from another application like Microsoft Word. In your VBA code, both the expressions Application.ActiveWorkbook.Name and ActiveWorkbook.Name will have the same effect of returning the Active Workbook’s name. However, there are some instances when the Application qualifier is required to be used, viz. generally when using properties & methods which relate to the Excel window’s appearance, or which relate to how the excel application behaves as a whole.
The Active Object
If no Workbook or Worksheet is specified, Excel refers to the current Active Workbook or Worksheet by default. In your vba code you can also refer the current Active Workbook or Sheet as ActiveWorkbook or ActiveSheet. Both the expressions Worksheets(1).Name and ActiveWorkbook.Worksheets(1).Name will return the name of the first worksheet in the Active Workbook which also becomes the default object in this case. Similarly, both the expressions Range(«A1»).Value = 56 and ActiveSheet.Range(«A1»).Value = 56 will enter the value 56 in cell A1 of the Active Worksheet in the Active Workbook. This is a general rule that omitting reference to a Workbook or Worksheet refers to the current Active Workbook or Worksheet by default, but this rule is subject to below conditions.
Note : (i) omitting reference to a Worksheet when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, . ) will reference the specific sheet in whose module your code is entered and NOT the Active Sheet; and (ii) omitting reference to a Workbook when your vba code is entered in the Workbook module (ThisWorkbook) will reference the workbook in which your code is entered and NOT the Active Workbook. This means: (i) omitting reference to a Worksheet will default to ActiveSheet when your vba code is entered in Standard Code Modules (Module1, Module2, …) or the Workbook module (ThisWorkbook) and NOT when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, . ) or UserForms or any Class modules you create; and (ii) omitting reference to a Workbook will default to ActiveWorkbook when your vba code is entered in Standard Code Modules (Module1, Module2, …) or in the Sheet Modules (viz. Sheet1, Sheet2, . ) and NOT when your vba code is entered in the Workbook module (ThisWorkbook).
Access an Object / Access a Single Object from its Collection
Access a Workbook Object
Workbook Object and Workbooks Collection: All open Workbook objects in Excel are referred to as the Workbooks collection. You can access a single Workbook from the Workbooks Collection by using the workbook index. This index is either the workbook name or an index number, and is used as Workbooks(index). To activate a workbook named «VbaProject», use Workbooks(«VbaProject»).Activate. To activate the first workbook, use Workbooks(1).Activate. The index number starts at 1, which indicates the first workbook which is created or opened, and the last workbook number will be returned by Workbooks.Count (which counts the number of open workbooks). The activate the second workbook use Workbooks(2).Activate, to activate the last workbook use Workbooks(Workbooks.Count).Activate.
Access a Worksheet Object
Worksheet Object and Worksheets Collection: A Worksheets Collection object refers to all Worksheets contained in a workbook. Similar to a Workbook object, you can access a single Worksheet from the Worksheets Collection by using the worksheet index. The index can be the worksheet name or an index number, and is used as Worksheets(index). To activate a worksheet named «Sheet1», use Worksheets(«Sheet1»).Activate. To activate the first worksheet, use Worksheets(1).Activate. The index number starts at 1, which indicates the first worksheet, and the last worksheet number will be returned by Worksheets.Count (which counts the number of worksheets in a workbook). The activate the second worksheet use Worksheets(2).Activate, to activate the last worksheet use Worksheets(Worksheets.Count).Activate.
Access a Sheet Object
Sheet Object and Sheets Collection: A Sheets Collection object refers to all sheets contained in a workbook, which includes chart sheets and worksheets. You can access a single Sheet from the Sheets Collection by using the sheet index viz. Sheets(index), similar to accessing a Worksheet. The Sheet index can be the sheet name viz. Sheets(«Sheet1»).Activate, or index number viz. Sheets(1).Activate or Sheets(Sheets.Count).Activate.
Access a Range Object
A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. You can refer to a range by using the following expressions.
Referencing a single cell:
Enter the value 10 in the cell A1 of the worksheet named «Sheet1»:
Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:
ActiveSheet.Cells(2, 3).Value = 10
Referencing a range of cells:
Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:
ActiveSheet.Range(«A1», «B3»).Value = 10
ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10
Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:
Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:
Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:
Select all the cells of the active worksheet:
Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:
ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»
Referencing Row(s) or Column(s):
Select all the Rows of active worksheet:
Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:
Select all the Columns of the active worksheet:
Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:
Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:
Relative Referencing:
Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:
Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:
Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:
Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:
Properties and Methods of Objects
As explained above, to manipulate an Object you can Set its Properties and Call its Methods.
To access the property of an object, connect the Object Name to the Property by inserting a period (full stop or dot) between them viz. Worksheets(1).Name, returns the name of the first worksheet. Some objects have default properties viz. a Range object’s default property is Value and you can omit to mention Value. In this case using Range(«A1»).Value or only Range(«A1») is the same and will return the value or content of the Cell A1, and the expressions can be used alternatively. Properties can be: (i) a Read-only property, which means you can read or access but cannot change it; or (ii) a Read-write property, in which case your VBA code can both read or change value.
To access the method of an object, connect the Object Name to the Method by inserting a period (full stop or dot) between them viz. Worksheets(1).Activate, activates the first worksheet by calling the Activate method. A Method may or may not have argument(s). An argument is a value supplied to a method to enable it to perform an action. To use the Calculate & Activate Method on a Worksheet object, you need not supply an argument viz. Worksheets(«Sheet1»).Calculate or Worksheets(«Sheet1»).Activate. To use the Add Method on a Worksheets Collection Object, you need to supply multiple arguments.
An Object’s Method is a procedure that acts on it. A Method can have Arguments which are required to be specified and/or it can have Optional Arguments which you can omit to specify. Arguments which are displayed in square brackets in the method’s syntax, are optional while others are required. The arguments can be supplied in the order of the position in which they are defined in the method syntax, each argument value being separated with a comma even for optional arguments which may not be specified. Alternatively the arguments can be supplied by the argument name (referred as named arguments) in which case the position in which they are specified becomes irrelevant. Each Named argument will also be separated with a comma, but not for optional arguments which are not specified. While specifying named arguments, you specify the argument name followed by a colon and an equal sign (:=) which is followed by the argument value, viz. ArgumentName:= «ArgumentValue» . Using named arguments will facilitate keeping a track of the arguments which have been specified and those which have been omitted.
Examples of using an Object’s Method:
The Activate Method applied to a Worksheet Object, activates the specified worksheet and makes it current. This method has no argument(s).
The Add Method applied to a Worksheets Collection Object, creates a new worksheet. It has multiple arguments, all of which are Optional. Syntax: Worksheets.Add(Before, After, Count, Type).
Using the Add Method without specifying any argument — adds a new worksheet before the Active Worksheet because both the Before & After arguments are omitted (note that the default value of Count argument is 1):
Using the Add Method specifying one named argument of After — adds a new worksheet after the Worksheet named «Sheet2» (note that the default value of Count argument is 1):
Using the Add Method specifying two named arguments of After & Count — adds 3 new worksheets after the Worksheet named «Sheet2»:
Worksheets.Add After:=Worksheets(«Sheet2»), Count:=3
Using the Add Method specifying two positional arguments of After & Count — adds 2 new worksheets after the Worksheet named «Sheet2»:
Worksheets.Add , Worksheets(«Sheet2»), 2
Using the Add Method specifying two positional arguments of Before & Count — adds 2 new worksheets before the Worksheet named «Sheet2»:
Worksheets.Add Worksheets(«Sheet2»), , 2
Using the Add Method specifying one named argument of Before — adds a new worksheet before the Worksheet named «Sheet2», and using the Name property, names the new worksheet «NewSheet»:
Working with Objects in Excel VBA
Excel VBA IntelliSense
While writing vba code, when you type an Object followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense). Ensure that the Excel VBA IntelliSense is turned on: in VBE, Tools>Options>Editor, ‘Auto List Members’ should be selected/checked. For instance, the IntelliSense will pop up after you type range followed by a period viz. range.[Intellisense for a Range object Pops Up]. Refer Image 2 — properties of the Range object are indicated by the fingers and methods of the Range object are indicated by the green boxes/bricks. You can either type or else select from this pop-up list, the method or property you want to connect with the object.
Using With…End With Statement to refer to Objects
As explained earlier, to access an Object and its properties & methods, you have to use the object name. In your vba code you will often need to refer to an object multiple times, and each time you will have to use its name. Instead of using the object name every time, you can execute multiple code lines which repeatedly refer to an object, by using the With…End With Statement. You start the block with the first line as:- type the With keyword followed by the Object Name. Insert one or more code lines after the first line:- access the object’s members (its properties, methods, etc) by typing a period (dot) followed by the property or method name, and you need not specify the object name each time. Terminate the block with the end line:- «End With». Refer to the below example, which shows how to make your vba code more readible using a With Block, and with Nesting ie. Block within a Block:
‘use the With . End With statement to refer to a Range object
With Worksheets(«Sheet1»).Range(«A1»)
‘use the Value property of the Range object, to set the value for the range:
.Value = 11
‘use the Name property, of the Range object, to set the range name:
.Name = «Score»
‘use the Font Property of the Range object that returns a Font object, and then use the With . End With statement to refer to the Font object
With .Font
‘note that because you are using the With . End With statement to refer to the Font object within the Range object, you will not refer to both the range or font objects below:
‘use the Name property of the Font object to set the font name:
.Name = «Arial»
‘use the Bold property of the Font object to set the font to bold:
.Bold = True
‘use the Color property of the Font object to set the font color:
‘use the Borders property of the Range object to return all four borders (Borders collection object), and then use the LineStyle property of the Borders object to add a double border:
.Borders.LineStyle = xlDouble
‘the Clear Method of the Range object, clears the range (clears the contents, formulas and formatting):
Using Variables in VBA
A variable is a named storage location used to store temporary values or information for use in execution of the code. In your vba program, a variable stores data and its content is used or changed later while executing the code. By declaring a variable for use in your code, you tell the Visual Basic compiler the variable’s data type (type of value it represents viz. integer, decimal, text, boolean, etc.) and other information such as its scope/level (what code can access it — variables can be Procedure Level, Module Level or can have a Public scope). Variables must be explicitly declared using the Dim, Private, Public, ReDim, or Static statements. When you declare variables by using a Dim statement (Dim is short for dimension): for declaring a variable to hold an Integer value, use «Dim rowNumber As Integer»; for declaring a variable to hold text values, use «Dim strEmployeeName As String»; and so on.
Keywords in VBA
Keywords are reserved words that VBA uses as part of its programming language. Keywords are words or commands that are recognized by VBA and can be used in vba code only as part of the vba language (like in a statement, function name, or operator) and not otherwise (like sub-procedure or variable names). Examples of keywords are: Sub, End, Dim, If, Next, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, and so on. To get help on a particular keyword, insert your mouse cursor within the keyword (in your vba code in VBE ) and press F1. Note that Keywords get capitalized in the vba code indicating that they have been written correctly viz. typing next will automatically appear as Next.
Assign an Object to a Variable, using the Set Keyword
In VBA, you use the Set keyword to assign an object reference. To assign an object to a variable in your vba code, you need to use the Set keyword as shown below. Note that using the Dim, Private or Public statements you only declare a variable as to its data type (type of value it represents viz. integer, text, etc.) and other information such as its scope/level (what code can access it). The actual object is assigned or referred to it only by using the Set statement. It is shorter to use an object variable & also more convenient because its data type will be known by VBA so that when you type the variable followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense).
Example : With the following code, we declare a variable (myRange) of Range data type, and then assign the Range object to this variable using the Set keyword, so that every time you want to refer to the specific Range, you can do so by using the variable. The following will enter the value 10 in cells A1 to C3 in the worksheet named «Sheet1».
Источник
“High aims form high characters, and great objects bring out great minds” – Tryon Edwards
A Quick Guide to VBA Objects
Task | Examples |
---|---|
Declare and Create | Dim coll As New Collection Dim o As New Class1 |
Declare Only | Dim coll As Collection Dim o As Class1 |
Create at run time | Set coll = New Collection Set o = New Class1 |
Assign to Excel Object | Dim wk As Workbook Set wk = Workbooks(«book1.xlsx») |
Assign using CreateObject | Dim dict As Object Set dict = CreateObject(«Scripting.Dictionary») |
Assign to existing object | Dim coll1 As New Collection Dim coll2 As Collection Set coll2 = coll1 |
Return from Function | Function GetCollection() As Collection
Dim coll As New Collection End Function |
Receive from Function | Dim coll As Collection Set coll = GetCollection |
The Webinar
If you are a member of the website, click on the image below to view the webinar for this post.
(Note: Website members have access to the full webinar archive.)
Introduction
If you are serious about learning VBA then it is important to understand VBA Objects. Using objects is not that difficult. In fact, they make your life much easier.
In this post, you will see how VBA makes brilliant use of objects. How objects such as Collections, Workbooks and Worksheets save you much complexity, time and effort.
In my next post, I will cover creating objects using Class Modules. However, before you create your own it is vital that you understand exactly what they are and why you need them.
So grab your favourite beverage and take a journey into the fascinating world of VBA objects.
What is a VBA Object?
To understand what an object is, we must first look at simple variables. In VBA we have basic data types such as string, integers, double and date.
We use these data types when we are creating a variable e.g.
Dim Score As Long, Price As Double Dim Firstname As String, Startdate As Date Score = 45 Price = 24.55 Firstname = "John" Startdate = #12/12/2016#
Basic VBA variables have only one purpose. To store a value while our application is running. We either put a value in the variable or read a value from the variable.
Dim Marks As Long ' Store value in Marks Marks = 90 Marks = 34 + 44 Marks = Range("A1") ' Read value from Marks Range("B2") = Marks Debug.Print Marks
In VBA we have a Collection which we use to store groups of items. The following code shows an example of using a Collection in VBA
' https://excelmacromastery.com/ Sub UseCollection() Dim collFruit As New Collection ' Add item to the collection collFruit.Add "Apple" collFruit.Add "Pear" ' Get the number of items in the collection Dim lTotal As Long lTotal = collFruit.Count End Sub
The Collection is an example of an object. It is more than a variable. That is, it does more than storing a piece of data. We can add items, remove items and get the number of items.
Definition of a VBA Object: An object is a grouping of data and procedures(i.e. Functions and Subs). The procedures are used to perform some task related to the data.
In the Collection the data is the group of the items it stores. The procedures such as Add, Remove, Count then act on this data.
In the Worksheet object, the main data item is the worksheet and all the procedures perform actions related to the worksheet.
Why VBA Uses Objects
An object is used to represent real world or computer based items.
The major benefit of an object is that it hides the implementation details. Take the VBA Collection we looked at above. It is doing some complicated stuff. When an item is added it must allocate memory, add the item, update the item count and so on.
We don’t know how it is doing this and we don’t need to know. All that we need to know is when we use Add it will add the item, Remove will remove the item and Count will give the number of items.
Using objects allows us to build our applications as blocks. Building it this way means you can work on one part without affecting other parts of your application. It also makes it easier to add items to an application. For example, a Collection can be added to any VBA application. It is not affected in any way by the existing code and in turn it will not affect the existing code.
A Real World Analogy
Looking at a real-world example can often be a good way to understand concepts.
Take a car with a combustion engine. When you are driving your car, a lot of complex stuff is happening. For example, fuel gets injected, compressed and ignited leading to combustion. This then causes the wheels of your car to turn.
A nice looking combustion engine | © BigStockPhoto.com
The details of how this happens are hidden from you. All you expect is that turning the key will start the car, pressing the accelerator will speed it up and pressing the brake will slow it down and so on.
Think of how great your code would be if it was full of these type of objects. Self-contained and dedicated to performing one set of tasks really well. It would make building your applications so much easier.
Object Components
There are three main items that an object can have. These are
- Properties – These are used to set or retrieve a value.
- Methods – These are function or subs that perform some task on the objects data.
- Events – These are function or subs that are triggered when a given event occurs
If you look in the Object Browser(F2) or use Intellisense you will notice different icons beside the members of an object. For example, the screenshot below shows the first three members of the Worksheet object
What these icons mean is as follows
Let’s take a look at the first three members of the worksheet.
It has an Activate method which we can use to make worksheet active.
It has an Activate event which is triggered when the worksheet is activated.
The Application property allows us to reference the application(i.e. Excel).
' Prints "Microsoft Excel" Debug.Print Sheet1.Application.Name ' Prints the worksheet name Debug.Print Sheet1.Name
In the next sections we will look at each of these components in more detail.
Object Properties
An object property allows us to read a value from the object or write a value to the object. We read and write to a property the same way we read and write to a variable.
' Set the name sheet1.Name = "Accounts" ' Get the name sName = sheet1.Name
A property can be read-only which means we can read the value but we cannot update the value.
In the VBA Range, Address is a read-only property
' The address property of range Debug.Print Sheet1.Range("A1").Address
The workbook property Fullname is also a read-only property
' The Fullname property of the Workbook object
sFile = ThisWorkbook.Fullname
Properties can also Set and Get objects. For example, the Worksheet has a UsedRange property that return a Range object
Set rg = Sheet1.UsedRange
You will notice we used the Set keyword here. We will be looking at this in detail later in the post.
Object Methods
A method is a Sub or a Function. For example, Add is a method of the Collection
' Collection Add method Coll.Add "Apple"
Methods are used to perform some action to do with the object data. With a Collection, the main data is the group of items we are storing. You can see that the Add, Remove and Count methods all perform some action relating to this data.
Another example of a method is the Workbook SaveAs method
Dim wk As Workbook Set wk = Workbooks.Open "C:DocsAccounts.xlsx" wk.SaveAs "C:DocsAccounts_Archived.xlsx"
and the Worksheets Protect and Copy methods
sheet1.Protect "MyPassword"
Sheet1.Copy Before:=Sheet2
Object Events
Visual Basic is an event-driven language. What this means is that the code runs when an event occurs. Common events are button clicks, workbook Open, worksheet Activate etc.
In the code below we display a message each time Sheet1 is activated by the user. This code must be placed in the worksheet module of Sheet1.
Private Sub Worksheet_Activate() MsgBox "Sheet1 has been activated." End Sub
Now that we know the parts of the VBA object let’s look at how we use an object in our code.
Creating a VBA Object
In VBA, our code must “Create” an object before we can use it. We create an object using the New keyword.
If we try to use an object before it is created we will get an error. For example, take a look at the code below
Dim coll As Collection coll.Add "Apple"
When we reach the Add line no Collection has been created.
If we try to run this line we get the following error
There are three steps to creating a VBA object
- Declare the variable.
- Create a new object.
- Assign the variable to the object.
We can perform these steps in one line using Dim and New together. Alternatively, we can declare the variable in one line and then create and assign the object in another line using Set.
Let’s take a look at both of these techniques.
Using Dim with New
When we use Dim and New together they declare, create and assign all in one line.
' Declare, Create and Assign Dim coll As New Collection
Using code like does not provide much flexibility. It will always create exactly one Collection when we run our code.
In the next section we will look at Set. This allows us to create objects based on conditions and without having to declare a variable for each new object.
Using Set with New
We can declare an object variable in one line and then we can use Set to create and assign the object on another line. This provides us with a lot of flexibility.
In the code below we declare the object variable using Dim. We then create and assign it using the Set keyword.
' Declare Dim coll As Collection ' Create and Assign Set coll = New Collection
We use Set in this way when the number of objects can vary. Using Set allows us to create multiple objects. In other words, we can create objects as we need them. We can’t do this using Dim and New.
We can also use conditions to determine if we need to create an object e.g.
Dim coll As Collection ' Only create collection if cell has data If Range("A1") <> "" Then Set coll = New Collection End If
Later in this post we will see some examples of using Set to create objects.
Subtle Differences of Dim Versus Set
There are some subtle differences between using New with Set and using New with Dim.
When we use New with Dim, VBA does not create the object until the first time we use it.
In the following code, the collection will not be created until we reach the line that adds “Pear”.
Dim coll As New Collection ' Collection is created on this line coll.Add "Pear"
If you put a breakpoint on the Add line and check the variable value you will see the following message
Object variable or With block variable not set
When the Add line runs, the Collection will be created and the variable will now show a Collection with one item.
The reason for this is as follows. A Dim statement is different to other VBA lines of code. When VBA reaches a Sub/Function it looks at the Dim statements first. It allocates memory based on the items in the Dim statements. It is not in a position to run any code at this point.
Creating an object requires more than just allocating memory. It can involve code being executed. So VBA must wait until the code in the Sub is running before it can create the object.
Using Set with New is different in this regard to using Dim with New. The Set line is used by VBA when the code is running so VBA creates the object as soon as we use Set and New e.g.
Dim coll As Collection ' Collection is created on this line Set coll = New Collection coll.Add "Pear"
There is another subtlety to keep in mind using New. If we set the object variable to Nothing and then use it again, VBA will automatically create a new object e.g.
' https://excelmacromastery.com/ Sub EmptyColl2() ' Create collection and add items Dim coll As New Collection ' add items here coll.Add "Apple" ' Empty collection Set coll = Nothing ' VBA automatically creates a new object coll.Add "Pear" End Sub
If we used Set in the above code to create the new Collection then the “Add Pear” line would cause an error.
When New Is Not Required
You may have noticed some objects don’t use the New keyword.
Dim sh As Worksheet Set sh = ThisWorkbook.Worksheets("Sheet1")
Dim wk As Workbook Set wk = Workbooks.Open("C:DocsAccounts.xlsx")
When a workbook, is opened or created, VBA automatically creates the VBA object for it. It also creates the worksheet object for each worksheet in that workbook.
Conversely, when we close the workbook VBA will automatically delete the VBA objects associated with it.
This is great news. VBA is doing all the work for us. So when we use Workbooks.Open, VBA opens the file and creates the workbook object for the workbook.
An important point to remember is that there is only one object for each workbook. If you use different variables to reference the workbook they are all referring to the same object e.g.
Dim wk1 As Workbook Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx") Dim wk2 As Workbook Set wk2 = Workbooks("Accounts.xlsx") Dim wk3 As Workbook Set wk3 = wk2
We will look at this in more detail in the VBA Objects in Memory section below.
Using CreateObject
There are some very useful libaries that are not part of Excel VBA. These include the Dictionary, Database objects, Outlook VBA objects, Word VBA objects and so on.
These are written using COM interfaces. The beauty of COM is that we can easily use these libraries in our projects.
If we add a reference to the library we create the object in the normal way.
' Select Tools->References and place a check ' beside "Microsoft Scripting Runtime" Dim dict As New Scripting.Dictionary
If we don’t use a reference we can create the object at run time using CreateObject.
Dim dict As Object Set dict = CreateObject("Scripting.Dictionary")
The first method is referred to as Early Binding and the second is referred to as Late Binding(see Early versus Late Binding) for more details.
Assigning VBA Objects
We can assign basic variables using the Let keyword.
Dim sText As String, lValue As Long Let sText = "Hello World" Let lValue = 7
The Let keyword is optional so nobody actually uses it. However, it is important to understand what it is used for.
sText = "Hello World"
lValue = 7
When we assign a value to a property we are using the Let Property
' Both lines do the same thing sheet1.Name = "Data" Let sheet1.Name = "Data"
When we assign an object variable we use the Set keyword instead of the Let keyword. When I use “object variable” I mean any variable that isn’t a basic variable such as a string, long or double etc..
' wk is the object variable Dim wk As Worksheet Set wk = ThisWorkbook.Worksheets(1) ' coll1 is the object variable Dim coll1 As New Collection coll1.Add "Apple" ' coll2 is the object variable Dim coll2 As Collection Set coll2 = coll1
Using the Set keyword is mandatory. If we forget to use Set we will get the error below
coll2 = coll1
It may look like Let and Set are doing the same thing. But they are actually doing different things:
- Let stores a value
- Set stores an address
To understand more about this we need to take a peek(pun intended:-)) into memory.
VBA Objects in Memory
“Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it” – Alan Perlis
To understand what New and Set are doing we need to understand how variables are represented in memory.
When we declare variables, VBA creates a slot for them in memory. You can think of the slot as an Excel cell in memory.
Dim X As long, Y As Long
When we assign values to these variables, VBA places the new values in the appropriate slots.
X = 25 Y = 12
We saw the following line of code earlier in this post
Dim coll As New Collection
This line creates the object in memory. However, it doesn’t store this object in the variable. It
stores the address of the object
in the variable. In programming, this is known as a Pointer.
Because VBA handles this seamlessly it can seem as if the object variable and the object are the same thing. Once we understand they are different it is much easier to understand what Set is actually doing.
How Set Works
Take a look at the following code
Dim coll1 As New Collection Dim coll2 As Collection Set coll2 = coll1
Only one Collection has been created here. So coll1 and coll2 refer to the same Collection.
In this code, coll1 contains the address of the newly created Collection.
When we use Set we are copying the address from coll1 to coll2. So now they are both “pointing” to the same Collection in memory.
Earlier in the post we looked at Workbook variables. Let’s have a look at this code again
Dim wk1 As Workbook Set wk1 = Workbooks.Open("C:DocsAccounts.xlsx") Dim wk2 As Workbook Set wk2 = Workbooks("Accounts.xlsx") Dim wk3 As Workbook Set wk3 = Workbooks(2)
When we open the workbook Accounts.xlsx, VBA creates an object for this workbook. When we assign the workbook variables in the code above, VBA places the address of the workbook object in the variable.
In this code example, the three variables are all referring to the same workbook object.
If we use code like the following
wk1.SaveAs "C:TempNewName.xlsx"
VBA uses the address in wk1 to determine the workbook object to use. It does this seamlessly so when we use a workbook variable it looks like we are referring directly to the object.
To sum up what we have learned in this section:
- Let writes a value to a basic variable
- Set writes an address to an object variable
Objects and Procedures
In VBA we can refer to Functions and Subs as procedures. When we pass an object to a procedure only the address passed.
When we pass an object from a Function(Subs cannot return anything) only the address of the object is passed back.
In the code below we have one collection. It is the address that gets passed to and from the function.
' https://excelmacromastery.com/ Sub TestProc() ' Create collection Dim coll1 As New Collection coll1.Add "Apple" coll1.Add "Orange" Dim coll2 As Collection ' UseCollection passes address back to coll2 Set coll2 = UseCollection(coll1) End Sub ' Address of collection passed to function Function UseCollection(coll As Collection) _ As Collection Set UseCollection = coll End Function
Using ByRef and ByVal
When we pass a simple variable to a procedure we can pass using ByRef or ByVal.
ByRef means we are passing the address of the variable. If the variable changes in the procedure the original will also be changed.
ByVal means we are creating a copy of the variable. If the variable changes in the procedure the original will not be changed.
' Pass by value Sub PassByVal(ByVal val As Long) ' Pass by reference Sub PassByRef(ByRef val As Long) Sub PassByRef(val As Long)
Most of the time it is a good idea to use ByVal because it prevents the variable being accidentally changed in a procedure.
When we pass a Collection to a procedure, we are always passing the address of the Collection.
ByRef and ByVal only affect the object variable. They do not affect the object!
What this means is that if we change the object in the procedure it will be changed outside it – this is regardless of whether you use ByVal or ByRef.
For example, in the code below we have two procedures that change the Collection. One uses ByRef and one uses ByVal. In both cases the Collection has changed when we return to the TestProcs Sub
' https://excelmacromastery.com/ Sub TestProcs() Dim c As New Collection c.Add "Apple" PassByVal c ' Prints Pear Debug.Print c(1) PassByRef c ' Prints Plum Debug.Print c(1) End Sub ' Pass by value Sub PassByVal(ByVal coll As Collection) ' Remove current fruit and add Pear coll.Remove (1) coll.Add "Pear" End Sub ' Pass by reference Sub PassByRef(ByRef coll As Collection) ' Remove current fruit and add Plum coll.Remove (1) coll.Add "Plum" End Sub
Let’s look at a second example. Here we are setting the object variable to “point” to a new Collection. In this example, we get different results from ByVal and ByRef.
In the PassByVal Sub, a copy of the original object variable is created. So it is this copy that points to the new Collection. So our original object variable is not affected.
In the PassByRef Sub we are using the same object variable so when we point to the New Collection, our original object variable is now pointing to the new collection.
' https://excelmacromastery.com/ Sub TestProcs() Dim c As New Collection c.Add "Apple" PassByVal c ' Prints Apple as c pointing to same collection Debug.Print c(1) PassByRef c ' Prints Plum as c pointing to new Collecton Debug.Print c(1) End Sub ' Pass by value Sub PassByVal(ByVal coll As Collection) Set coll = New Collection coll.Add "Orange" End Sub ' Pass by reference Sub PassByRef(ByRef coll As Collection) Set coll = New Collection coll.Add "Plum" End Sub
Why VBA Uses Pointers
You may be wondering why VBA uses pointers. The reason is that it is much more efficient.
Imagine you had a Collection with 50000 entries. Think how inefficient it would be to create multiple copies of this Collection when your application was running.
Think of it like a library which is a real world collection of books. We can put the Library address in directories, newspapers etc. A person simply uses the address to go to the Library and add and remove books.
There is one Libary and the address is passed around to anyone who needs to use it.If we wanted a second library we would create a new library. It would have a different address which we could also pass around.
© BigStockPhoto.com
Running a Simple Memory Experiment
To demonstrate what we have been discussing, let’s look at a code example. The code below uses
- VarPtr to give the memory address of the variable
- ObjPtr to give the memory address of the object
The memory address is simply a long integer and it’s value is not important. But what is interesting is when we compare the addresses.
' https://excelmacromastery.com/ Sub Memory() Dim coll1 As New Collection Dim coll2 As Collection Set coll2 = coll1 ' Get address of the variables Coll1 and Coll2 Dim addrColl1 As Long, addrColl2 As Long addrColl1 = VarPtr(coll1) addrColl2 = VarPtr(coll2) Debug.Print "Address of the variable coll1 is " & addrColl1 Debug.Print "Address of the variable coll2 is " & addrColl2 ' Get address of the Collection they point to Dim addrCollection1 As Long, addrCollection2 As Long addrCollection1 = ObjPtr(coll1) addrCollection2 = ObjPtr(coll2) Debug.Print "Address coll1 collection is " & addrCollection1 Debug.Print "Address coll2 collection is " & addrCollection2 End Sub
Note: Use LongPtr instead of Long if you are using a 64 bit version of Excel.
When you run the code you will get a result like this:
Address of the variable coll1 is 29356848
Address of the variable coll2 is 29356844
Address coll1 collection is 663634280
Address coll2 collection is 663634280
you will notice
- The memory addresses will be different each time you run.
- The address of the coll1 Collection and the coll2 Collection will always be the same.
- The address of the coll1 variable and the coll2 variable will always be different.
This shows that we have two different variables which contain the address of the same Collection.
Cleaning Up Memory
So what happens if we set a variable to a New object multiple times? In the code below we use Set and New twice for the variable coll
Dim coll As Collection Set coll = New Collection coll.Add "Apple" ' Create a new collection and point coll to it Set coll = New Collection
In this example, we created two new Collections in memory. When we created the second collection we set coll to refer to it. This means it no longer refers to the first collection. In fact, nothing is referring to the first Collection and we have no way of accessing it.
In some languages(looking at you C++) this would be a memory leak. In VBA however, this memory will be cleaned up automatically. This is known as Garbage Collection.
Let me clarify this point. If an object has no variable referring to it, VBA will automatically delete the object in memory. In the above code, our Collection with “Apple” will be deleted when coll “points” to a new Collection.
Clean Up Example
If you want to see this for yourself then try the following.
Create a class module, call it clsCustomer and add the following code.
Public Firstname As String Private Sub Class_Terminate() MsgBox "Customer " & Firstname & " is being deleted." End Sub
Class_Terminate is called when an object is being deleted. By placing a message box in this event we can see exactly when it occurs.
Step through the following code using F8. When you pass the Set oCust = New clsCustomer line you will get a message saying the Jack was deleted.When you exit the function you will get the message saying Jill was deleted.
' https://excelmacromastery.com/ Sub TestCleanUp() Dim oCust As New clsCustomer oCust.Firstname = "Jack" ' Jack will be deleted after this line Set oCust = New clsCustomer oCust.Firstname = "Jill" End Sub
VBA automatically deletes objects when they go out of scope. This means if you declare them in a Sub/Function they will go out of scope when the Function ends.
Setting Objects to Nothing
In code examples you may see code like
Set coll = Nothing
A question that is often asked is “Do we need to Set variables to Nothing when we are finished with them?”. The answer is most of the time you don’t need to.
As we have seen VBA will automatically delete the object as soon as we go out of scope. So in most cases setting the object to Nothing is not doing anything.
The only time you would set a variable to Nothing is if you needed to empty memory straight away and couldn’t wait for the variable to go out of scope. An example would be emptying a Collection.
Imagine the following project. You open a workbook and for each worksheet you read all the customer data to a collection and process it in some way. In this scenario, you would set the Collection to Nothing every time you finish with a worksheet’s data.
' https://excelmacromastery.com/ Sub SetToNothing() ' Create collection Dim coll As New Collection Dim sh As Worksheet ' Go through all the worksheets For Each sh In ThisWorkbook.Worksheets ' Add items to collection ' Do something with the collection data ' Empty collection Set coll = Nothing Next sh End Sub
Memory Summary
To sum up what we have learned in this section:
- A new object is created in memory when we use the New keyword.
- The object variable contains only the memory address of the object.
- Using Set changes the address in the object variable.
- If an object is no longer referenced then VBA will automatically delete it.
- Setting an object to Nothing is not necessary in most cases.
Why Set Is Useful
Let’s look at two examples that show how useful Set can be.
First, we create a very simple class module called clsCustomer and add the following code
Public Firstname As String Public Surname As String
Set Example 1
In our first scenario, we are reading from a list of customers from a worksheet. The number of customers can vary between 10 and 1000.
Obviously, declaring 1000 objects isn’t an option. Not only is it a lot of wasteful code, it also means we can only deal with maximum 1000 customers.
' Don't do this!!! Dim oCustomer1 As New clsCustomer Dim oCustomer2 As New clsCustomer ' . ' . ' . Dim oCustomer1000 As New clsCustomer
What we do first is to get the count of rows with data. Then we create a customer object for each row and fill it with data. We then add this customer object to the collection.
' https://excelmacromastery.com/ Sub ReadCustomerData() ' We will always have one collection Dim coll As New Collection ' The number of customers can vary each time we read a sheet Dim lLastRow As Long lLastRow = Sheet1.Range("A" & Sheet1.Rows.Count).End(xlUp).Row Dim oCustomer As clsCustomer Dim i As Long ' Read through the list of customers For i = 1 To lLastRow ' Create a new clsCustomer for each row Set oCustomer = New clsCustomer ' Add data oCustomer.Firstname = Sheet1.Range("A" & i) oCustomer.Surname = Sheet1.Range("B" & i) ' Add the clsCustomer object to the collection coll.Add oCustomer Next i End Sub
Each time we use Set we are assigning oCustomer to “point” to the newest object. We then add the customer to the Collection. What happens here is that VBA creates a copy of the object variable and places it in the collection.
Set Example 2
Let’s look at a second example where using Set is useful. Imagine we have a fixed number of customers but only want to read the ones whose name starts with the letter B. We only create a customer object when we find a valid one.
' https://excelmacromastery.com/ Sub ReadCustomerB() ' We will always have one collection Dim coll As New Collection Dim oCustomer As clsCustomer, sFirstname As String Dim i As Long ' Read through the list of customers For i = 1 To 100 sFirstname = Sheet1.Range("A" & i) ' Only create customer if name begins with B If Left(sFirstname, 1) = "B" Then ' Create a new clsCustomer Set oCustomer = New clsCustomer ' Add data oCustomer.Firstname = sFirstname oCustomer.Surname = Sheet1.Range("B" & i) ' Add to collection coll.Add oCustomer End If Next i End Sub
It doesn’t matter how many customer names start with B this code will create exactly one object for each one.
This concludes my post on VBA Objects. I hope you found it beneficial.In my next post I’ll be looking at how you can create your own objects in VBA using the Class Module.
If you have any questions or queries please feel free to add a comment or email me at Paul@ExcelMacroMastery.com.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Object Properties
A property refers to what an object has.
As an analogy, a car has a predefined set of properties such as color, size, type, engine, etc.
Likewise, an Excel object could have its own set of properties, such as color, font, and value.
Properties come after the object hierarchy.
This means that the object is specified first, followed by a period, then the property name, and the details or value assigned to it.
It also has to be specific in cases where there might be some ambiguity.
Taking a car and a shoe as examples:
Car.Color – might be too broad
Car.Interior.Color = Black – this makes sure that Excel knows which part of the car is being referred to.
Property Details
There are different property scenarios in Excel
- Some properties don’t have details
- Range(“A1”).Address
- Range(“A1”).Value
- Some properties return an object – this occurs when an object’s property is also an object with its own properties
- Range(“A2”).Interior.Color – The Range A2 has Interior as its property, while Interior has Color as its property.
- Range(“A2”).Font.Color
An interior property returns an interior object.
More details on this can be found through Microsoft Help.
Property Type
A property can be either read-only, write, or both.
Below are some use cases:
- Range(“A1”).Value = ActiveCell.Address
- This reads the address of the active cell and puts it as the value of cell A1.
- Range(“A1”).Interior.Color = vbRed
- This assigns the color red to cell A1’s interior.
- Range(“A1”).Font.Color = vbBlue
- This changes the font color of cell A1 to blue.
Object Methods
A method dictates what to do with an object or what an object does.
Taking a car for an example, its methods can be:
- Start
- Stop
- Crash
Method arguments
Some methods don’t have arguments, while some methods have additional arguments or information.
For example, how do you want to start the car?
Quickly or slowly?
This then becomes:
Car.Stop Quickly.
Methods can also change properties.
For a car, the “Crash” method would change the “Size” property of the car.
Ways of writing arguments
- Using a space
- Car.Stop Quickly
- Assign a name of an argument and assign a value using :=
- Car.Stop StopStyle:= Quickly
Below are some examples:
- Clear – no further arguments
- Range(“A2”).Clear
- Delete([Shift]) – can have 1 argument that determines if you want to shift to the left, right, etc.
- Range(“A2”).Delete xlShiftToLeft
- This deletes cell A2 and shifts the table to the left.
- Range(“A2”).Delete xlShiftToLeft
- Copy([Destination])– 1 argument for destination
- Range(“A3”).Copy Range(“B3”)
- This copies cell A3 to cell B3.
- Range(“A3”).Copy Range(“B3”)
- Copy([Before], [After])– 2 optional and exclusive arguments which can be written in two ways
- Sheet1.Copy After:=Sheet3
- Copy Sheet1 Sheet3.
- Sheet1.Copy , Sheet2
- Skip the [Before] argument and skip to the [After] argument
- Sheet1.Copy After:=Sheet3
- PasteSpecial – detailed pasting (formatting, transposed, etc.)
- After – detailed pasting (formatting, transposed, etc.)
Published on: April 5, 2018
Last modified: February 23, 2023
Leila Gharani
I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.
My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.
Excel VBA Objects; Excel Object Model; Access a Workbook, Worksheet or Range Object; Set Object Properties & Call its Methods
————————————————————————————
Contents:
VBA Objects
The Excel Object Model
Active Object
Access an Object / Access a Single Object from its Collection
Properties and Methods of Objects
Working with Objects in Excel VBA
————————————————————————————
An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object, a Method is an action performed by an object. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. An object is a thing which contains data and has properties and methods. To manipulate an Object you will Set its Properties and Call its Methods.
For more articles related to Excel VBA objects: Excel VBA Application Object, the Default Object in Excel; Excel VBA Workbook Object, working with Workbooks in Excel; Microsoft Excel VBA — Worksheets; Excel VBA Range Object, Referencing Cells and Ranges; Excel VBA Custom Classes and Objects.
Visual Basic is not truly an Object-Orientated Programming (OOP) Language
Visual Basic (Visual Basic 6) is not truly an Object-Orientated Programming (OOP) Language whereas its successor Visual Basic.NET (part of the .NET platform) is a full-fledged Object Oriented programming language meeting the criteria of encapsulation, inheritance and polymorphism, where everything in Visual Basic.NET can be treated as an object. Visual Basic has many (but not all) elements of an Object-Orientated Programming (OOP) language. VBA deals with objects but is not truly an Object-Orientated Programming language.
VBA Objects
An object is a thing which contains data and has properties and methods. Properties are the characteristics or attributes that describe the object (like name, color, size) or define an object’s behaviour (viz. if visible or enabled). An object’s data or information can be accessed with properties (viz. Value property, Name property). A Method is an action performed by an object. Calling a Method will execute a vba code which will cause the object to perform an action. You can associate objects with nouns, properties with adjectives and methods with verbs. An object could be a house, car, table or pen. Properties of a car include its color or size, which describe it. A car can perform actions of moving, accelerating or turning which are its methods. Examples of objects in Excel are workbook, worksheet, range, command button, font, etc. A Range object has «Value» as one of its properties and «Select» as one of its methods. Similarly a worksheet has, among others, a «Name» property, a «Delete» method, and a «Copy» method having arguments which contain information in respect of the worksheet to be copied.
Objects also have event procedures attached to them. Events are actions performed, or occurrences, which trigger a VBA code or macro. An event procedure (ie. a vba code) is triggered when an event occurs such as opening / closing / saving / activating / deactivating the workbook, selecting a cell or changing cell selection in a worksheet, making a change in the content of a worksheet cell, selecting or activating a worksheet, when a worksheet is calculated, and so on. Excel provided built-in event procedure — an Event Procedure is automatically invoked when an object recognizes the occurrence of an event. Event procedures are attached to objects like Workbook, Worksheet, Charts, Application, UserForms or Controls. Event Procedures are triggered by a predefined event and are installed within Excel having a standard & predetermined name viz. like the Worksheet change procedure is installed with the worksheet — «Private Sub Worksheet_Change(ByVal Target As Range)». In the Worksheet Change event procedure, the Worksheet object is associated with the Change event, which means that with the worksheet change event, a sub-procedure containing customized code runs automatically when you change the contents of a worksheet cell. Custom Events — you can also define your own events in custom classes (class modules), and create event procedures that run when those events occur.
A Collection Object in vba refers to a group of related items, as a single object. Many objects are present both in single form as well as in multiples. For example: (i) Workbook & Workbooks — all open Workbook objects in Excel are referred to as the Workbooks collection; (ii) Worksheet & Worksheets — A Worksheets Collection object refers to all Worksheets contained in a workbook. All elements (items) of a collection share the same properties and methods, though they do not need to be of the same data type. You can either create your own collection using the vba Collection class or use the Excel VBA built-in collections such as Worksheets (the Worksheets Collection Object includes all Worksheets in a workbook). With a Collection Object you can work with all objects (which are its elements) as a group as against working with a single object. The basic ways of working with elements of a collection include: adding an element using the Add method, removing an element using the Remove method, determining the number of elements contained in a collection using the Count property, accessing a specific element using the Item property, enumerate each element of a collection using the For Each…Next Statement, and so on.
The Excel Object Model
All applications like Excel, Access, Word or PowerPoint, which use VBA, have their own object model. While writing vba code in Microsoft Office Excel, you will be using the objects provided by the Excel object model. The object model is a large hierarchy of all the objects used in VBA. When you use vba in an Office Application, say PowerPoint, a reference to the PowerPoint Object Library is set by default. When you Automate to work with PowerPoint objects from another application, say Excel, you can add a reference to the PowerPoint object library in Excel (your host application) by clicking Tools-References in VBE, which will enable using PowerPoint’s predefined constants — the PowerPoint objects, properties, and methods will appear in the Object Browser and the syntax will be checked at compile time.
All objects, and their associated Properties and Methods, available in Excel VBA can be viewed in the Object Browser in the VBE code window — in VBE click on View>Object Browser or press F2. On the top-left of the window is the Project/Library box, which by default mentions <All Libraries>, wherein you can choose Excel from the list to view all Excel objects. On the left pane of the window the available Classes (Objects) are listed, and on the right pane are displayed all Members (ie. properties, methods, events & constants) associated with the selected object in the Classes list. Global members (ie. properties, methods, events & constants) are those in respect of which the object name can be omitted. In the Excel Object Library, those properties and methods whose use does not require specifying the Application object qualifier are considered «global». Refer Image 1 to view the Object Browser.
The Object Model of the Application (Excel) refers to and contains its programming objects which are related to each other in a hierarchy. The entire Excel application is represented by the Application Object which is at the top of the Excel object hierarchy and moving down you can access the objects from Application to Workbook to Worksheet to Range (Cells) and further on, by connecting the objects with a period (dot). Excel objects are accessed through ‘parent’ objects — Worksheet is the parent of the Range Object, and the Workbook is the parent of the Worksheet object, and the Application object is the parent of the Workbook object.
Example — Start at the top of the hierarchy with the Application object, then move down to the workbook, worksheet, range and font objects, as follows:
Application.ActiveWorkbook.Worksheets(1).Range(«A1»).Font
The Excel Object Model hierarchy — the most used objects:
The Application Object refers to the host application of Excel, and the entire Excel application is represented by it. The Workbook Object, appears next below the Application Object in Excel object hierarchy, and represents a single workbook within the Excel application. A workbook is also referred to as an Excel file. The Workbooks Collection Object includes all currently open Workbooks in Excel. The Worksheet Object, appears next below the Workbook Object in Excel object hierarchy, and represents a single worksheet within the workbook. The Worksheets Collection Object includes all Worksheets in a workbook. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells (when the Range is a union of multiple blocks of cells it is referred as a non-contiguous range of cells). The Range object is usually used maximum within the Excel application.
The Application object is the Default Object, Excel assumes it even when it is not specified. The Application qualifier is mostly not required to be used in vba code, because the default application is Excel itself, unless you want to refer to other outside applications (like Microsoft Word or Access) in your code or you want to refer to Excel from another application like Microsoft Word. In your VBA code, both the expressions Application.ActiveWorkbook.Name and ActiveWorkbook.Name will have the same effect of returning the Active Workbook’s name. However, there are some instances when the Application qualifier is required to be used, viz. generally when using properties & methods which relate to the Excel window’s appearance, or which relate to how the excel application behaves as a whole.
The Active Object
If no Workbook or Worksheet is specified, Excel refers to the current Active Workbook or Worksheet by default. In your vba code you can also refer the current Active Workbook or Sheet as ActiveWorkbook or ActiveSheet. Both the expressions Worksheets(1).Name and ActiveWorkbook.Worksheets(1).Name will return the name of the first worksheet in the Active Workbook which also becomes the default object in this case. Similarly, both the expressions Range(«A1»).Value = 56 and ActiveSheet.Range(«A1»).Value = 56 will enter the value 56 in cell A1 of the Active Worksheet in the Active Workbook. This is a general rule that omitting reference to a Workbook or Worksheet refers to the current Active Workbook or Worksheet by default, but this rule is subject to below conditions.
Note: (i) omitting reference to a Worksheet when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) will reference the specific sheet in whose module your code is entered and NOT the Active Sheet; and (ii) omitting reference to a Workbook when your vba code is entered in the Workbook module (ThisWorkbook) will reference the workbook in which your code is entered and NOT the Active Workbook. This means: (i) omitting reference to a Worksheet will default to ActiveSheet when your vba code is entered in Standard Code Modules (Module1, Module2, …) or the Workbook module (ThisWorkbook) and NOT when your vba code is entered in Sheet Modules (viz. Sheet1, Sheet2, …) or UserForms or any Class modules you create; and (ii) omitting reference to a Workbook will default to ActiveWorkbook when your vba code is entered in Standard Code Modules (Module1, Module2, …) or in the Sheet Modules (viz. Sheet1, Sheet2, …) and NOT when your vba code is entered in the Workbook module (ThisWorkbook).
Access an Object / Access a Single Object from its Collection
Access a Workbook Object
Workbook Object and Workbooks Collection: All open Workbook objects in Excel are referred to as the Workbooks collection. You can access a single Workbook from the Workbooks Collection by using the workbook index. This index is either the workbook name or an index number, and is used as Workbooks(index). To activate a workbook named «VbaProject», use Workbooks(«VbaProject»).Activate. To activate the first workbook, use Workbooks(1).Activate. The index number starts at 1, which indicates the first workbook which is created or opened, and the last workbook number will be returned by Workbooks.Count (which counts the number of open workbooks). The activate the second workbook use Workbooks(2).Activate, to activate the last workbook use Workbooks(Workbooks.Count).Activate.
Access a Worksheet Object
Worksheet Object and Worksheets Collection: A Worksheets Collection object refers to all Worksheets contained in a workbook. Similar to a Workbook object, you can access a single Worksheet from the Worksheets Collection by using the worksheet index. The index can be the worksheet name or an index number, and is used as Worksheets(index). To activate a worksheet named «Sheet1», use Worksheets(«Sheet1»).Activate. To activate the first worksheet, use Worksheets(1).Activate. The index number starts at 1, which indicates the first worksheet, and the last worksheet number will be returned by Worksheets.Count (which counts the number of worksheets in a workbook). The activate the second worksheet use Worksheets(2).Activate, to activate the last worksheet use Worksheets(Worksheets.Count).Activate.
Access a Sheet Object
Sheet Object and Sheets Collection: A Sheets Collection object refers to all sheets contained in a workbook, which includes chart sheets and worksheets. You can access a single Sheet from the Sheets Collection by using the sheet index viz. Sheets(index), similar to accessing a Worksheet. The Sheet index can be the sheet name viz. Sheets(«Sheet1»).Activate, or index number viz. Sheets(1).Activate or Sheets(Sheets.Count).Activate.
Access a Range Object
A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. You can refer to a range by using the following expressions.
Referencing a single cell:
Enter the value 10 in the cell A1 of the worksheet named «Sheet1»:
Worksheets(«Sheet1»).Range(«A1»).Value = 10
Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:
ActiveSheet.Cells(2, 3).Value = 10
Referencing a range of cells:
Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:
ActiveSheet.Range(«A1:B3»).Value = 10
ActiveSheet.Range(«A1», «B3»).Value = 10
ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10
Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:
Worksheets(«Sheet1»).Range(«A1,B3»).Value = 10
Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:
ActiveWorkbook.Worksheets(«Sheet3»).Range(«B2:D3,H7»).Interior.Color = vbRed
Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:
Range(«Score»).Value = 10
ActiveSheet.Range(«Score»).Value = 10
Select all the cells of the active worksheet:
ActiveSheet.Cells.Select
Cells.Select
Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:
ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»
ActiveSheet.Cells.Font.Size = 11
Cells.Font.Size = 11
Referencing Row(s) or Column(s):
Select all the Rows of active worksheet:
ActiveSheet.Rows.Select
Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:
Worksheets(«Sheet1»).Rows(2).Value = 10
Select all the Columns of the active worksheet:
ActiveSheet.Columns.Select
Columns.Select
Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:
ActiveSheet.Columns(3).Value = 10
Columns(«C»).Value = 10
Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:
Worksheets(«Sheet1»).Columns(«A:C»).Value = 10
Relative Referencing:
Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:
Range(«C5:E8»).Range(«A1») = 10
Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:
Range(«C5:E8»).Range(«B2») = 10
Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:
Range(«C5»).Offset(1, 2) = 10
Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:
Range(«C5:E8»).Offset(2, 3) = 10
Properties and Methods of Objects
As explained above, to manipulate an Object you can Set its Properties and Call its Methods.
To access the property of an object, connect the Object Name to the Property by inserting a period (full stop or dot) between them viz. Worksheets(1).Name, returns the name of the first worksheet. Some objects have default properties viz. a Range object’s default property is Value and you can omit to mention Value. In this case using Range(«A1»).Value or only Range(«A1») is the same and will return the value or content of the Cell A1, and the expressions can be used alternatively. Properties can be: (i) a Read-only property, which means you can read or access but cannot change it; or (ii) a Read-write property, in which case your VBA code can both read or change value.
To access the method of an object, connect the Object Name to the Method by inserting a period (full stop or dot) between them viz. Worksheets(1).Activate, activates the first worksheet by calling the Activate method. A Method may or may not have argument(s). An argument is a value supplied to a method to enable it to perform an action. To use the Calculate & Activate Method on a Worksheet object, you need not supply an argument viz. Worksheets(«Sheet1»).Calculate or Worksheets(«Sheet1»).Activate. To use the Add Method on a Worksheets Collection Object, you need to supply multiple arguments.
An Object’s Method is a procedure that acts on it. A Method can have Arguments which are required to be specified and/or it can have Optional Arguments which you can omit to specify. Arguments which are displayed in square brackets in the method’s syntax, are optional while others are required. The arguments can be supplied in the order of the position in which they are defined in the method syntax, each argument value being separated with a comma even for optional arguments which may not be specified. Alternatively the arguments can be supplied by the argument name (referred as named arguments) in which case the position in which they are specified becomes irrelevant. Each Named argument will also be separated with a comma, but not for optional arguments which are not specified. While specifying named arguments, you specify the argument name followed by a colon and an equal sign (:=) which is followed by the argument value, viz. ArgumentName:= «ArgumentValue». Using named arguments will facilitate keeping a track of the arguments which have been specified and those which have been omitted.
Examples of using an Object’s Method:
The Activate Method applied to a Worksheet Object, activates the specified worksheet and makes it current. This method has no argument(s).
Worksheets(«Sheet1»).Activate
The Add Method applied to a Worksheets Collection Object, creates a new worksheet. It has multiple arguments, all of which are Optional. Syntax: Worksheets.Add(Before, After, Count, Type).
Using the Add Method without specifying any argument — adds a new worksheet before the Active Worksheet because both the Before & After arguments are omitted (note that the default value of Count argument is 1):
Worksheets.Add
Using the Add Method specifying one named argument of After — adds a new worksheet after the Worksheet named «Sheet2» (note that the default value of Count argument is 1):
Worksheets.Add After:=Worksheets(«Sheet2»)
Using the Add Method specifying two named arguments of After & Count — adds 3 new worksheets after the Worksheet named «Sheet2»:
Worksheets.Add After:=Worksheets(«Sheet2»), Count:=3
Using the Add Method specifying two positional arguments of After & Count — adds 2 new worksheets after the Worksheet named «Sheet2»:
Worksheets.Add , Worksheets(«Sheet2»), 2
Using the Add Method specifying two positional arguments of Before & Count — adds 2 new worksheets before the Worksheet named «Sheet2»:
Worksheets.Add Worksheets(«Sheet2»), , 2
Using the Add Method specifying one named argument of Before — adds a new worksheet before the Worksheet named «Sheet2», and using the Name property, names the new worksheet «NewSheet»:
Worksheets.Add(Before:=Worksheets(«Sheet2»)).Name = «NewSheet»
Working with Objects in Excel VBA
Excel VBA IntelliSense
While writing vba code, when you type an Object followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense). Ensure that the Excel VBA IntelliSense is turned on: in VBE, Tools>Options>Editor, ‘Auto List Members’ should be selected/checked. For instance, the IntelliSense will pop up after you type range followed by a period viz. range.[Intellisense for a Range object Pops Up]. Refer Image 2 — properties of the Range object are indicated by the fingers and methods of the Range object are indicated by the green boxes/bricks. You can either type or else select from this pop-up list, the method or property you want to connect with the object.
Using With…End With Statement to refer to Objects
As explained earlier, to access an Object and its properties & methods, you have to use the object name. In your vba code you will often need to refer to an object multiple times, and each time you will have to use its name. Instead of using the object name every time, you can execute multiple code lines which repeatedly refer to an object, by using the With…End With Statement. You start the block with the first line as:- type the With keyword followed by the Object Name. Insert one or more code lines after the first line:- access the object’s members (its properties, methods, etc) by typing a period (dot) followed by the property or method name, and you need not specify the object name each time. Terminate the block with the end line:- «End With». Refer to the below example, which shows how to make your vba code more readible using a With Block, and with Nesting ie. Block within a Block:
‘use the With … End With statement to refer to a Range object
With Worksheets(«Sheet1»).Range(«A1»)
‘use the Value property of the Range object, to set the value for the range:
.Value = 11
‘use the Name property, of the Range object, to set the range name:
.Name = «Score»
‘use the Font Property of the Range object that returns a Font object, and then use the With … End With statement to refer to the Font object
With .Font
‘note that because you are using the With … End With statement to refer to the Font object within the Range object, you will not refer to both the range or font objects below:
‘use the Name property of the Font object to set the font name:
.Name = «Arial»
‘use the Bold property of the Font object to set the font to bold:
.Bold = True
‘use the Color property of the Font object to set the font color:
.Color = vbRed
‘use the Borders property of the Range object to return all four borders (Borders collection object), and then use the LineStyle property of the Borders object to add a double border:
.Borders.LineStyle = xlDouble
‘the Clear Method of the Range object, clears the range (clears the contents, formulas and formatting):
End With
Using Variables in VBA
A variable is a named storage location used to store temporary values or information for use in execution of the code. In your vba program, a variable stores data and its content is used or changed later while executing the code. By declaring a variable for use in your code, you tell the Visual Basic compiler the variable’s data type (type of value it represents viz. integer, decimal, text, boolean, etc.) and other information such as its scope/level (what code can access it — variables can be Procedure Level, Module Level or can have a Public scope). Variables must be explicitly declared using the Dim, Private, Public, ReDim, or Static statements. When you declare variables by using a Dim statement (Dim is short for dimension): for declaring a variable to hold an Integer value, use «Dim rowNumber As Integer»; for declaring a variable to hold text values, use «Dim strEmployeeName As String»; and so on.
Keywords in VBA
Keywords are reserved words that VBA uses as part of its programming language. Keywords are words or commands that are recognized by VBA and can be used in vba code only as part of the vba language (like in a statement, function name, or operator) and not otherwise (like sub-procedure or variable names). Examples of keywords are: Sub, End, Dim, If, Next, And, Or, Loop, Do, Len, Close, Date, ElseIf, Else, Select, and so on. To get help on a particular keyword, insert your mouse cursor within the keyword (in your vba code in VBE ) and press F1. Note that Keywords get capitalized in the vba code indicating that they have been written correctly viz. typing next will automatically appear as Next.
Assign an Object to a Variable, using the Set Keyword
In VBA, you use the Set keyword to assign an object reference. To assign an object to a variable in your vba code, you need to use the Set keyword as shown below. Note that using the Dim, Private or Public statements you only declare a variable as to its data type (type of value it represents viz. integer, text, etc.) and other information such as its scope/level (what code can access it). The actual object is assigned or referred to it only by using the Set statement. It is shorter to use an object variable & also more convenient because its data type will be known by VBA so that when you type the variable followed by the period (dot), all the methods and properties of the object will appear in a pop-up list (Excel VBA IntelliSense).
Example: With the following code, we declare a variable (myRange) of Range data type, and then assign the Range object to this variable using the Set keyword, so that every time you want to refer to the specific Range, you can do so by using the variable. The following will enter the value 10 in cells A1 to C3 in the worksheet named «Sheet1».
Dim myRange As Range
Set myRange = Worksheets(«Sheet1»).Range(«A1:C3»)
myRange.Value = 10