Excel objects properties and methods

Содержание

  1. Общие сведения об объектах, методах, свойствах и событиях
  2. Объекты и коллекции
  3. Возврат объектов
  4. Методы
  5. Свойства
  6. События
  7. См. также
  8. Поддержка и обратная связь
  9. Understanding objects, methods, properties, and events
  10. Objects and collections
  11. Returning objects
  12. Methods
  13. Properties
  14. Events
  15. See also
  16. Support and feedback
  17. VBA Objects Properties and Methods in Excel
  18. VBA Reference
  19. 120+ Project Management Templates
  20. What are Objects?
  21. What are Properties?
  22. What are Methods?
  23. VBA Objects Properties and Methods in Excel – Object Browser?
  24. Excel VBA
  25. 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».

Источник

Skip to content

VBA Objects Properties and Methods in Excel

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?
  • What are Properties?
  • What are Methods?
  • Object Browser?

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.

Objects-Example-1

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…

Sub sbExampleRangeProperties()
Range("A1").Value = 25
Range("A1").Interior.ColorIndex = 5
End Sub

Objects-Example-2

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.

Sub sbExampleRangeMethods()
    Range("A1").Select
    Selection.Copy
    Range("B5").Select
    ActiveSheet.Paste
End Sub

Objects-Example-3

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.
Objects-Example-4

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management 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
Excel VBA Project Management Templates
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

Related Posts

    • What are Objects?
    • What are Properties?
    • What are Methods?
    • VBA Objects Properties and Methods in Excel – Object Browser?

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:

9 Comments

  1. NAGESWARA RAO
    January 6, 2015 at 2:37 PM — Reply
  2. Yogarajah
    October 6, 2015 at 8:44 AM — Reply

    Very simple explanation of objects,Properties and Methods in VBA. Congratulation.

  3. Nafis
    April 18, 2016 at 10:09 AM — Reply

    Thanks, deep explanation in very simple way. it clears the concept very easily.

    Thanks again.

  4. hemant
    June 11, 2016 at 2:38 PM — Reply

    Good ,simple explaination

  5. Ashok
    October 22, 2016 at 10:01 AM — Reply

    It is very easy and simple to understand the subject

  6. Vignesh
    May 8, 2017 at 4:41 PM — Reply
  7. Sivaji
    May 19, 2017 at 11:47 PM — Reply

    Thank u sooo much dear gud explanation

  8. Remmy
    August 8, 2017 at 12:39 PM — Reply

    I bought a massive VBA book on Amazon and having read it over and over again, it still couldn’t understand properly what these things are. You, however, nailed it in a few word. Thank you.

  9. PNRao
    August 8, 2017 at 2:18 PM — Reply

    We are glad to hear that you this useful.
    Thank you very mach!

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

An object has properties and methods. Excel Visual Basic is a semi-object oriented programming language. Learn more about the object hierarchy of Excel Visual Basic.

In Excel VBA, objects, properties and methods are connected with a dot. Properties are something which an object has (they describe the object), while methods do something (they perform an action with an object).

What is Excel VBA Property ?

Let’s take a look at an Excel VBA object and an Excel VBA property. We will use the Range object and the Formula property. The Range object is nothing more than a cell (or cells) on your worksheet.

We already know from Excel that a cell can contain a formula.

1. Place the value 10 into cell A1.

2. Create a command button.

3. Add the line:

Range(“B1”).Formula = Range(“A1”) * 2

4. Execute the macro. This macro places the formula into cell B1 and the result will be calculated (20).

What is Excel VBA Method ?

We will use the Range object again and the ClearContents method.

1. Place the value 10 into cell A1.

2. Create a command button.

3. Add the line:

Range(“A1”).ClearContents

4. Execute the macro. Cell A1 is now empty!

How to see all the properties and methods of an object ?

The Range object has many more properties and methods. Want to see more?

1. Launch the Visual Basic Editor.

2. Type in: Range.

3. A list will appear showing you all the Excel VBA methods and properties of the Range object. The fingers are the properties and the green boxes are the methods of the Range object.

Workbook and Worksheet:

The Worksheet and Workbook object have properties and methods as well, such as the count property which counts the number of active workbooks or worksheets. The Workbook and Worksheet object are commonly used in Excel VBA. They are very useful when your macro code has to be executed on different workbooks or worksheets.

What is Object Hierarchy ?

Now that we have seen the Range object, we can understand the Workbook and Worksheet object better. In Excel Visual Basic each object can contain another object, and that object can contain another object, etc. In other words, Excel VBA programming involves working with an object hierarchy.

The main hierarchy of all objects is Excel itself. We call it the Application object. The application object contains other objects. An example of an object of the Application object is the Workbook object (Excel File). This can be any workbook you have created. The Workbook object contains other objects, such as the Worksheet object. The Worksheet object contains other objects, such as the Range object.

We have used the following code line a lot:

Range(“A1”).Value

but what we really meant was cell A1 on the first worksheet of Book1. Thus we should actually add the following line in Excel VBA:

Application.Workbooks(“Book1”).Worksheets(1).Range(“A1”).Value

Fortunately we do not have to add a code line this way. This is because Excel Visual Basic knew we meant Book1 and the first worksheet because we placed our command button there (remember?). Now also remember the automatically created module when we recorded a macro with the Excel Macro Recorder. Code placed into a module is available to all workbooks and worksheets.

Place the Sub test into a module (In the Visual Basic Editor, click on Insert and then Module).

Sub test()

Range(“A1”).Value = “code placed here”

End Sub

  1. Execute the code (Click on Macros and then Run, or click on Run from the Visual Basic Editor). The words “code placed here” will be placed into cell A1.
  2. Now go to the second worksheet. Execute the code again. You will see that the words will be placed on the second worksheet as well!
  3. Now even open a new workbook and execute the macro again. You will see that the words will be placed there as well! That is because we didn’t specify a workbook or worksheet name and Excel VBA automatically takes the active workbook and active worksheet. Be aware that if you want to change different things on different sheets to include the Worksheet object

Below are few Properties and methods of the Workbook and Worksheet object :

You may have noticed that worksheets and workbooks are both plural (see the complete code line mentioned earlier). That’s because they are actually collections. The Workbooks collection contains all the Workbook objects that are currently open. The Worksheets collection contains all the Worksheet objects in a workbook.

You can refer to a member of the collection, that is: a single workbook or single worksheet, in two ways. Using the index number, Worksheets(1) is the first worksheet starting from the left. Using the member’s name: Worksheets(“sheet1”).

Below are few examples.

1. The Count property of the Worksheets collection and Workbooks collection. The following code line counts the number of worksheets of a workbook. Place a command button on your worksheet and add the code line:

MsgBox Worksheets.Count

Result when you click the command button on the sheet:

You can also use the Count property to count the number of active workbooks.

2. The Add method of the Workbooks collection and Worksheets collection. The following code line creates a new worksheet.

Worksheets.Add
You can also use the Add method to add a new workbook.

3. The Worksheet object contains more interesting collections, such as the Rows collection. In Excel VBA you can use the Select method to select a row. The code line below selects row 2

Worksheets(1).Rows(2).Select

In a similar way, you can select a column. The code line below selects column 7.

Worksheets(1).Columns(7).Select

What is Application Object ?

The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.

The mother of all objects is Excel itself. We call it the Application object. The application object gives access to a lot of Excel related options.

Thank you for reading. Happy Learning!

Excel VBA Tutorial about Object MethodsIf you’re in the process of learning Visual Basic for Applications, there are a few basic topics you need to thoroughly understand. I have explained some of these in other blog posts that you can find at the Power Spreadsheets Archive.

However, at the most basic level, the following 3 topics are perhaps the most basic things you need to learn and understand in order to start making useful things with VBA:

  1. Objects.
  2. Object properties.
  3. Object methods.

You can read some of the tutorials I’ve written about the first 2 topics here, here (for objects), and here (for properties). This blog post focuses on the third item in the list above:

Methods.

More precisely, I explain the most important aspects you need to know in order to start working with object methods in VBA. You can use the following table of contents to navigate directly to any section you’re most interested in. Make sure to read the full post in any case 😉 .

OK. Let’s go straight into the topic of today’s post and take a closer look at…

What Are Object Methods In VBA And Why Are They Important

There’s no question that knowing about VBA objects is extremely important. To achieve something of practical value, you must do something with/to the object(s) you work with.

Therefore, you must know about VBA objects in order to become a great Excel VBA programmer. However, this isn’t enough on its own…

You also need to know and understand how you can manipulate those objects. And this is where object methods and object properties come in:

Methods are the actions or operations you perform with an object (by or on the object). Properties, on the other hand, are the attributes or characteristics you can use to describe the object.

According to a common analogy (between VBA and the parts of speech in the English language), you can think of:

  • Objects as akin to nouns.
  • Properties as analogous to adjectives.
  • Methods as corresponding to verbs.

It’s not possible to communicate fluently in English by just using nouns (without also using adjectives and verbs). Similarly, you can’t build appropriate VBA applications by just using objects (without also including properties and methods).

The ability of specifying the action to be applied to an object allows you to use methods for the following 2 main purposes:

  • Purpose #1: Make an object do something.
  • Purpose #2: Modify the properties of an object. Consider (for ex.) the Range.ClearContents method. The Range.ClearContents method:
    • Clears values and formulas from the applicable cell range.
    • (Generally) Results in a change to the applicable Range.Value property (the cell range’s value).

This applies to object collections as well. The reason for this, as explained here, is that collections are themselves objects.

However, in order to ensure that you do a great job with the object methods you’ll need to use, let’s take a look at…

How To Work With Object Methods In VBA

Let’s start to take a closer look at how you structure a statement that refers to (or calls/access) object methods. For these purposes, we’ll examine the following macro (called “Delete_Inactive_Worksheets”). The purpose of this Sub procedure is to delete all worksheets except for the one that’s currently active.

Sub Delete_Inactive_Worksheets()
    Dim my_Worksheet As Worksheet
    For Each my_Worksheet In ThisWorkbook.Worksheets
        If my_Worksheet.Name <> ThisWorkbook.ActiveSheet.Name Then
            Application.DisplayAlerts = False
            my_Worksheet.Delete
            Application.DisplayAlerts = True
        End If
    Next my_Worksheet
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following screenshot shows how the VBA code of the Delete_Inactive_Worksheets macro looks like in the Visual Basic Editor:

Example macro to illustrate VBA object properties

I won’t explain this particular macro line-by-line. For purposes of this Excel tutorial, we’ll focus on the following statement:

my_Worksheet.Delete

This statement is within the If…Then statement in the macro above. The relevant row of code is underlined in the following screenshot:

Macro example with highlighted VBA object method

This simple statement is enough to illustrate the basic rule to create references to object properties in Visual Basic for Applications:

You refer to (or call/access) a method by putting together the following 3 items:

  • Item #1: Name of the relevant VBA object. In the case above, this is the object variable my_Worksheet.
  • Item #2: A dot (.).
  • Item #3: Name of the method. In the case above, this is “Delete” or, more precisely, the Worksheet.Delete method.

In fact, most procedures have a number of lines following this basic structure:

Object.Method

Under this (basic) statement structure, the item after the dot (Method in the case above) acts on/with the item before the dot (Object in the case above).

One final note before we move on to the next section:

Note how, above, I mention specifically the Worksheet.Delete method instead of simply referring to the Delete method. This is important because a method may behave differently depending on the object it works with.

For example, when it comes to the Delete method, its syntax and precise behavior can be slightly different depending on whether it is applied to a Worksheet object (Worksheet.Delete method) or a Range object (Range.Delete method). Yes, in both cases the end result is that Excel deletes the relevant object. However:

  • When applied to a Range object, the Delete method has an extra argument (I explain method arguments below) which allows you to determine how Excel shifts the cells that replace any deleted cells.
  • When working with a Worksheet object, the method displays (by default) a dialog box asking you to confirm the worksheet deletion.

As you continue to work with Excel and Visual Basic for Applications, these nuances will become clearer. However, you may want to confirm that your choice of VBA object methods actually carry out the actions you want them to when working with the VBA objects you’re working with.

How To Work With The Arguments (Or Parameters) Of Object Methods In VBA

Arguments (also known as parameters) are, generally, what allows you to further determine the action that a method performs with an object.

In other words: Parameters allow you to determine “how” the action/method is carried out.

Going back to the parallel between VBA and the parts of speech of regular English, you can think of method arguments as being comparable to adverbs.

Some, but not all, object methods in VBA take arguments. Arguments can be mandatory or optional.

The topic of arguments is, actually, not as easy as you may think at first glance. In this section, we take a look at the most important aspects you must know in connection with this topic.

For purposes of illustrating how to work with the arguments of object methods in VBA, I make reference to the following simple macro (called “Copy_Main_Worksheet”). The Copy_Main_Worksheet macro (i) copies the worksheet called “Object Methods in VBA” and (ii) pastes the copy after the worksheet named “Sheet1”.

Sub Copy_Main_Worksheet()
    Worksheets("Object Methods In VBA").Copy After:=Worksheets("Sheet1")
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following image shows the VBA code of the Copy_Main_Worksheet within the Visual Basic Editor:

Example macro with object property argument

Let’s focus on the relevant statement of this macro, which is underlined in the image below:

VBA code example with object method arguments

You already know how to refer to object methods, the topic I explain above. Therefore, you probably identify the first part of the statement (“Worksheets(“Object Methods In VBA”).Copy”) as a reference that is divided in the following 3 items:

  • Item #1: “Worksheets(“Object Methods In VBA”)” makes reference to the Worksheet object named “Object Methods In VBA”.
  • Item #2: A dot (.) separates part #1 above from part #3 below.
  • Item #3: “Copy” makes reference to the Worksheet.Copy method.

The second part of the statement (“After:=Worksheets(“Sheet1″)”) is the part that sets the relevant method parameters. More precisely, it determines that the copied worksheet is placed after the sheet called “Sheet1”.

The Worksheet.Copy method has 2 optional but exclusive (you can only specify one of them) parameters:

  • Optional Parameter #1: “Before”, which determines which is the sheet in front of (or before) which the copied worksheet is placed.
  • Optional Parameter #2: “After”, which sets what is the sheet after which the copied worksheet is placed.
    • This is the parameter I use in this example. In other words: The copied worksheet is placed after “Sheet1”.

The following image breaks down the statement in the parts and items I explain above:

Macro explaining method arguments

This way of setting method parameters (which I explain below) isn’t the only syntax you can use. More precisely:

There are a few ways in which you can work with the arguments of object methods. In order to understand this better, let’s take a look at the most important ways in which you can specify the arguments for an object method in VBA:

Option #1: Basic Syntax To Specify Object Method Arguments

The Copy_Main_Worksheet macro that appears above doesn’t use the most basic form of syntax to specify method arguments. Although…

After going through this section you’ll probably:

  • Think that the basic syntax isn’t really that basic.
  • Understand why I use another syntax (which I explain below) in the version of the Copy_Main_Worksheet macro that appears above.

The following version of the Copy_Main_Worksheet macro uses the basic syntax to set the arguments of an object method. Notice the difference between both versions when it comes to referring to the method parameters.

Example of basic syntax VBA method property

I explain why there’s a comma (,) at the beginning of this part of the statement below. Excluding that comma, the basic syntax to specify arguments is relative straightforward:

Object.Method Argument_Value

In other words, to determine an argument for a VBA object method, you must:

  • Step #1: Refer to the object method appropriately by following the basic syntax explained above.
    • In the case above, this is “Worksheets(“Object Methods In VBA”).Copy”.
  • Step #2: Place a space ( ) after the name of the method.
  • Step #3: Place the relevant argument values.
    • In the example above, this is “, Worksheets(“Sheet1″)”.

You already know what “Worksheets(“Sheet1″)” does: It’s the After parameter that determines that the copied worksheet is placed after “Sheet1”.

That leaves the comma (,) at the beginning.

Syntax for several VBA object methods

This comma (,) appears because of the following 3 syntax rules:

  • When using more than 1 argument, use commas (,) to separate them.
  • When working with unnamed arguments, enter arguments in their default order.
  • When working with optional (and unnamed) arguments, use commas (,) to create blank placeholders for omitted arguments.
    • There are some cases where you don’t need to create placeholders for omitted arguments (for ex., when the argument you omit is at the end of the argument list).

In this case, the Worksheet.Copy method has 2 optional but exclusive arguments: Before and After. The Copy_Main_Worksheet uses only the second argument (After). Therefore, the VBA code that appears above includes a comma (,) and a blank placeholder for the unused Before argument.

As you see, the “basic” syntax to specify the arguments of a method isn’t that readable. And this was a single (and quite straightforward statement)…

Just imagine how it would be to work in a large and complex VBA application that uses this syntax and has plenty of methods with optional arguments and blank placeholders 😕 .

Fortunately, there is a second way in which you can set the parameters that clarify the action to be taken by a particular method. This is the syntax used in the original version of the Copy_Main_Worksheet macro above. Let’s take a look at it:

Option #2: Named Arguments

As implied by the description of this way of referring to the arguments of VBA object properties, you use the actual name of the argument when specifying it. More precisely, you use the following syntax:

Object.Method Argument_Name:=Argument_Value

In other words, when using named arguments you proceed as follows:

  • Step #1: Repeat the first 2 steps described above where I describe the basic syntax to specify the arguments of object methods.
    • In other words: (i) refer to the object method appropriately, and (ii) place a space after the name of the method.
  • Step #2: Write the (official) name of the argument.
  • Step #3: Place a colon and an equal sign (:=).
  • Step #4: Set the relevant argument value.

This is the syntax that I use in the first version of the Copy_Main_Worksheet macro that appears above.

Named argument for VBA object method

When you use named arguments for object methods in VBA, you don’t have to use any placeholder for the optional arguments that you don’t use. Therefore, in this case, there’s no placeholder at all for the missing Before argument of the Worksheets.Copy method.

You don’t need to use named arguments (is optional) and can get away with using the basic syntax described above. However, using named arguments has a few advantages over not using them, particularly the fact that named arguments improve the readability of your VBA code.

You can (theoretically):

  • Start specifying arguments using the basic syntax described above; and
  • Switch to named arguments at some point in the middle of the argument list. Once you include a named method argument, the remaining method arguments must (also) be named.

However, I don’t necessarily recommend this syntax.

Even though you can switch from non-named arguments to named arguments in the middle of a statement, you can’t do the opposite. In other words, you can’t start specifying parameters using named arguments and then switch to the basic syntax. Once you use named arguments once, you must continue working with named parameters for that particular line.

After comparing both syntax options for setting VBA object method parameters, you’ll probably agree that using named arguments is (as a general rule) a better practice.

Before we finish the topic of specifying arguments for object methods in VBA, let’s take a look at 2 additional clarifications regarding the syntax you use when setting VBA method arguments:

Referring To The Arguments Of Methods That Return A Value And Working With Default Argument Values

When working with methods that return a value or create new objects, you must (generally) wrap the arguments in parentheses. In such cases, as long as the arguments are within the parentheses, you can continue to use either of the 2 syntax options that I describe above (unnamed or named arguments).

Finally, note that several objects within Visual Basic for Applications have a particular default method value. You don’t necessarily have to provide a method value in such cases. This also applies to those methods that take more than 1 argument: some arguments may have default values while other don’t.

How To Access The Methods Of A Particular Object

A single object can have more than 1 associated method. In fact:

  • Some VBA objects have several dozen methods.
  • The Excel VBA Object Model contains thousands of methods.

But don’t feel overwhelmed!

In practice, you’re likely to work with a relatively small amount of VBA object methods over and over again. This is partly due to the fact that a single method can be associated to several VBA objects.

In other words: You’re unlikely to (in practice) work with certain methods.

However, it’s quite likely that (from time to time) you’ll need to search for a particular method while working with macros. Therefore, let’s take a look at some of the most common strategies you can use to find out the best VBA object method to achieve your goals in a particular situation.

In addition to the 3 strategies I explain below, you can also use the macro recorder to get some guidance about the objects, properties and methods you need.

Strategy #1: How To Make The Visual Basic Editor Display A List Of Methods

This is probably the easiest and most convenient way to explore the properties available for a particular VBA object. However, it only works if the Auto List Members setting of your Visual Basic Editor is enabled. In case you don’t have this setting enabled, I explain how to do it in this Excel tutorial.

In order to understand how you can make the VBE display a list of available methods, let’s go back to the code for the Delete_Inactive_Worksheets. More particularly, let’s assume that you’re typing the statement “my_Worksheet.Delete” (which I explain above) and you’re standing at the point where we must type the dot.

VBA code before VBE displays methods

Once you type the dot, the VBE displays a list of items that can be associated with that particular object. Therefore, in the case above, once you type the dot that follows my_Worksheet, the following list is shown:

VBA object method list displayed by VBE

This gives you a great idea of the properties and methods that you can use when working with a particular object. For example, if you scroll down enough, you can find the Delete method. This is the appropriate method to complete the statement above.

Delete method in list within VBE

In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled.

Strategy #2: Use The Object Browser

As explained by Chandoo (in the webpage I link to above), the Object Browser is a “helpful screen” that allows you to browse and understand VBA objects, properties and methods.

You can use the Object Browser to obtain all the available properties and methods for a particular object in 3 simple steps:

Step #1: Open The Object Browser

There are a few ways to access the Object Browser from within the Visual Basic Editor:

Step #2: Select The Excel Library

The drop-down list that appears on the top left corner of the Visual Basic Editor (“<All Libraries>”) displays all the object libraries that are available. Click on this drop-down menu and select Excel.

Select Excel library in Object Browser

Step #3: Select The Relevant Object Class

The Object Browser is divided in 2 sections:

  • Left section: Lists all the Excel objects.
  • Right section: Displays all the properties and methods that are available for the object that is currently selected on the left.

Therefore, in order to access the VBA methods of a particular object, search the object you want to explore on the left side of the Object Browser and click on it.

For example, in the case of sample macros used throughout this Excel tutorial, it’s interesting to see what happens when clicking on “Worksheet”. As you can see in the image below, the Object Browser displays a list of its members. This list includes both the Copy and Delete methods used by the Copy_Main_Worksheet and Delete_Inactive_Worksheets macro (respectively).

Methods available for Worksheet object in VBA

Strategy #3: Visit Microsoft’s Official Documentation

Microsoft’s Official Documentation has a massive amount of content regarding VBA objects and methods (among others).

One of the things you can use Microsoft’s Official Documentation for, is to get a list of all the methods that are available for a particular VBA object. To do this, simply follow these 4 easy steps:

Step #1: Type The Name Of An Object In The Visual Basic Editor

As an example, let’s go back to the Copy_Main_Worksheets used as an example above. Assume that you’re typing the only statement of this Sub procedure. Therefore, you type the relevant object which, in this case, is “Worksheets(“Object Methods In VBA”)”.

Example of object within macro

However, now that you’ve identified the VBA object, you want to see which methods can be used on that particular object.

Step #2: Place The Cursor On The Object

In the case above you can, for example, place the cursor within the word “Worksheets”, as shown below:

Cursor on object within VBE

Step #3: Press The F1 Key

F1 is the keyboard shortcut for opening the help system. In other words, this keyboard shortcut generally should either:

  • Take you to the relevant page within Microsoft’s Official Documentation; or
  • Ask you to confirm what the topic you want to help on is. This is the case, generally, when the Visual Basic Editor finds multiple instances of the word that you’ve selected.

In this particular case, once I press the F1 key, I’m led to the page about the Application.Worksheets property within the Microsoft Dev Center.

Help for VBE in MSDN

Step #4: Navigate To The Methods Of The Relevant Object

In some cases (such as the example above), you may need to do some navigation before you actually get to the appropriate object. The reason for this is that, most objects within VBA are accessed by using a property.

For example in the case above, the Application.Worksheets property is used to return a Worksheet object. Therefore, we’re originally taken to the webpage belonging to this particular property.

However, this navigation is usually not very complicated. In the case of the Application.Worksheets property, notice how Microsoft’s Official Documentation immediately explains that the property returns a collection (which is an object itself) representing worksheets. It also includes a link leading to the Sheet object (see image below).

Example of page in MSDN

In turn, the page covering the Sheets object explains how this collection “can contain Chart or Worksheet objects”. The website, again, displays a conspicuous link that you can click to get to the Worksheets object.

Example of MSDN website

In the case above, it took a little bit longer than usual to get to the appropriate page. However, once you’re in the page that makes reference to the relevant object, you can get Microsoft’s Official Documentation to show you all the available methods by expanding the list that appears on the left side of the page.

Methods in Microsoft Developer Network

In the case above, one of those available methods is indeed the Worksheet.Copy method used by the Copy_Main_Worksheet sample macro.

Access Worksheet.Copy method in MSDN

Conclusion

I mentioned at the beginning of this blog post that having a good understanding about VBA objects, properties and methods is essential in order to do any meaningful work with Visual Basic for Applications. This Excel tutorial has provided you with the fundamental knowledge you need in order to start using methods when coding in VBA. Among other topics, we’ve covered:

  • What are object methods in VBA, and why are they important.
  • How do you create references for a method.
  • How can you set the parameters or arguments of a particular method.
  • 3 different strategies you can use to find out what are the properties you can use when working with a particular VBA object.

Although VBA is not purely Object Oriented Programming language, it has the use of Objects. In this article, we are going to learn about Objects, Properties, and Methods in VBA.

So let us start learning.

What are Objects?

In the real world, everything is an object. A House, Window, Door, and the Car in the Garage.

In Excel, an object represents an element of the Application. We can think of a Workbook, Worksheet, Cell, Chart, Pivot Table, Report Table, etc. An Object once identified, can have its properties as well as methods.

We can also use a Collection (also an object) that contains several objects that might be of the same type. For Example, the Sheets Collection contains all the sheets objects of the workbook object. Similarly, a Forms Collection contains all the Form Objects in the Application.

infographics objects, properties and methods in vba

What are Properties?

A Property is an attribute of an Object. Properties define object characteristics like size or color or aspects of the behaviors like visible or enabled. If we need to change the characteristics of an object then we must change its properties.

For instance, a Car is an object and it can have different properties like Model, Engine, Fuel, Mileage, etc.

Similarly, the objects in Excel like Forms or Worksheets have their set of properties.

We can set the value of the property using the following syntax.

ObjectName.Property=Value

For example, we can change the Caption of a Form with this statement.

Myform.Caption = "Welcome"

We cannot set the values of all the properties of an object. A Read Write property allows us to change its value as well as read it. Some properties are Read Only and we cannot change their value. For example, we can only read the Address of a Cell Object. The Address Property cannot be changed so it is Read Only.

Sub sample()
MsgBox Range("A1").Address
End Sub

When you run this procedure, it prints the address of cell A1.

what are objects and properties in VBA

What are the Methods of an Object?

Methods refer to the action that can be performed using an object. A method might require arguments. Arguments provide additional information to the method about how we want to execute that functionality with the object. For example, we can call a number of methods of Range Object like Selecting a Range, Copying a Range, etc. In this example, we would copy the active cell and paste it to the destination cell within the current worksheet. Copy method of the Range object is used to copy the Range Object. We can also pass the Destination argument to Copy method. It specifies the range where we want to paste the Range Object Value.

Use the object.method. The Dot operator will show a list of all methods and properties for Range Object in VBE.

call a method of an object in vba
Sub Paste_single_cell()
'calling the Copy method of Range Object
Range("A1").Copy Destination:=Range("C1")            
End Sub

When we run this sub procedure, the contents of cell A1 is copied and pasted to cell C1.

Example – Adding Successive Dates as Sheet Name using VBA

We would now write a Sub Procedure that asks for a Start date. The name of the first sheet updates as per the start date and then the successive sheets are named with coming dates.

Let us say we have the following Six Worksheets in our Workbook.

Adding Successive Dates as Sheet Name using VBA

Use the following Sub Procedure.

Sub name_dates()
'Procedure to Add Successive Dates as Sheet Name
'input the start date from user
Dim start As Date
start = InputBox("Enter the start date:")


Dim ws As Worksheet     'ws is a Worksheet object helps us loop through all worksheets of workbook
    
Dim i As Integer        'i is used to get successive dates after start date
For Each ws In Sheets
    ws.Name = start + i     'assigning dates to each worksheet name
    i = i + 1
Next ws
End Sub
  • Press Alt and F8 keys and choose the Macro named name_dates and click on the Run button.
  • Enter the start date as 10-10-2002. (Or any other date that you wish)
Adding Successive Dates as Sheet Name using VBA example
  • After you click Ok, all the sheet name update as per the start date.

This was all about Objects, Properties, and Methods in VBA.

Thank you for reading.

RELATED POSTS

  • Object Browser in VBA

  • Worksheet Events in VBA Excel

  • Constants in VBA – Declaration, Types. Scope

  • Read and Write Cell Value using VBA

  • How to Use Active Cell in VBA

  • Write a Macro using VBA Editor – Command Button

Понравилась статья? Поделить с друзьями:
  • Excel object properties and methods
  • Excel object in html
  • Excel object in cell
  • Excel oart dll ошибка
  • Excel numeric to text