Содержание
- Создание переменных объекта
- Создание объектной переменной
- Объявление объектной переменной
- Назначение объектной переменной объекту
- Ссылка на текущий экземпляр объекта
- См. также
- Поддержка и обратная связь
- Функция CreateObject
- Синтаксис
- Примечания
- Пример
- См. также
- Поддержка и обратная связь
- VBA Objects
- Application Object
- Workbooks Object
- Workbook Object
- Sheets Object
- Worksheets Object
- Worksheet Object
- VBA Coding Made Easy
- Range Object
- Shapes Object
- Shape Object
- Excel VBA Object Model
- Declaring and Assigning an Object Variable
- VBA Code Examples Add-in
- Как работать с Excel через VBA или объектная модель Excel
- Объектная модель Excel
- Структура объектов
- Объекты и коллекции объектов
- Свойства объектов
- Методы объектов
- Приемы и лайфхаки
- Автоматическое заполнение кода по начальным символам
- Просмотр свойств и методов у объекта
- Явно указывайте тип переменных
- Быстрый просмотр справки
- Поиск по объектной модели
Создание переменных объекта
С объектной переменной можно обращаться точно так же, как объектом, к которому она относится. Вы можете задавать или возвращать свойства данного объекта или использовать любой из его методов.
Создание объектной переменной
Объявите эту объектную переменную.
Назначьте эту объектную переменную объекту.
Объявление объектной переменной
Используйте инструкцию Dim или одну из других инструкций объявления (Public, Private или Static), чтобы объявить переменную объекта. Переменная, ссылающаяся на объект, должна быть Variant, Object или объект определенного типа. Например, следующие объявления являются допустимыми:
Если вы используете объектную переменную, предварительно не объявив ее, типом данных объектной переменной по умолчанию является Variant.
Объявить объектную переменную с типом данных Object можно в случае, когда конкретный тип объекта неизвестен вплоть до запуска процедуры. Используйте тип данных Object для создания универсальной ссылки на любой объект.
Если конкретный тип объекта вам известен, следует объявлять объектную переменную как тип данного объекта. Например, если приложение содержит тип объекта Sample, можно объявить переменную объекта для этого объекта с помощью любой из следующих инструкций:
Объявление конкретных типов объектов обеспечивает автоматическую проверку типов, ускорение выполнения кода и улучшенную удобочитаемость.
Назначение объектной переменной объекту
Используйте инструкцию Set для назначения объекта переменной объекта. Можно назначить выражение объекта или Nothing. Например, допустимы следующие назначения переменных объекта.
Объявление переменной объекта можно объединить с присвоением ей объекта с помощью ключевого словаNew с оператором Set. Например:
Задание для объектной переменной значения Nothing прерывает связь этой объектной переменной с конкретным объектом. Это предотвращает случайное изменение объекта в результате изменения соответствующей переменной. Переменная объекта всегда имеет значение Nothing после закрытия связанного объекта, поэтому можно проверить, указывает ли переменная объекта на допустимый объект. Например:
Конечно, этот тест никогда не может с абсолютной уверенностью определить, закрыл ли пользователь приложение, содержащее объект, на который ссылается переменная объекта.
Ссылка на текущий экземпляр объекта
Используйте ключевое слово Me для ссылки на текущий экземпляр объекта, в котором выполняется код. Все процедуры, связанные с текущим объектом, имею доступ к объекту, на который ссылаются с использованием Me. Использование ключевого слова Me особенно полезно при передаче информации о текущем экземпляре объекта процедуре в другом модуле. Например, предположим, что имеется следующая процедура в модуле
Можно вызвать процедуру и передать текущий экземпляр объекта в качестве аргумента с помощью следующей инструкции:
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Функция CreateObject
Создает и возвращает ссылку на объект ActiveX.
Синтаксис
CreateObject(класс, [ имя_сервера ])
Синтаксис функции CreateObject состоит из следующих частей:
Часть | Описание |
---|---|
класс | Обязательный элемент, Variant (String). Имя приложения и класс создаваемого объекта. |
имя_сервера | Необязательный элемент, Variant (String). Имя сетевого сервера, где будет создан объект. Если имя_сервера является пустой строкой («»), используется локальный компьютер. |
Аргументкласса использует синтаксис appname. objecttype и состоит из следующих частей:
Part | Описание |
---|---|
имя_приложения | Обязательный элемент; Variant (String). Имя приложения, предоставляющего объект. |
тип_объекта | Обязательный элемент, Variant (String). Тип или класс создаваемого объекта. |
Примечания
Каждое приложение, поддерживающее автоматизацию, предоставляет как минимум один тип объекта. Например, в приложении для обработки текстов могут быть объекты Application, Document и Toolbar.
Чтобы создать объект ActiveX, назначьте объект, возвращаемый функцией CreateObject, переменной объекта.
Этот код запускает приложение, в котором создается объект, в данном случае электронная таблица Microsoft Excel. После создания объекта на него можно ссылаться в коде, используя переменную объекта. В приведенном ниже примере доступ к свойствам и методам нового объекта осуществлялся с помощью объектной переменной ExcelSheet и других объектов Microsoft Excel, включая объект Application и коллекцию Cells .
При объявлении объектной переменной с помощью предложения As Object создается переменная, которая может содержать ссылку на любой тип объекта. Однако обращение к объекту через эту переменную выполняется с поздним связыванием, то есть привязка создается при выполнении программы. Чтобы создать объектную переменную с ранним связыванием, то есть со связыванием при компиляции программы, объявите объектную переменную с определенным идентификатором класса. Например, можно объявить и создать следующие ссылки Microsoft Excel:
Ссылка с ранней привязкой может обеспечить большее быстродействие, но может содержать ссылку только на класс, указанный в объявлении.
Можно передать объект, возвращаемый функцией CreateObject, функции, которая использует объект в качестве аргумента. Например, в следующем коде создается и передается ссылка на объект Excel.Application:
Вы можете создать объект на удаленном компьютере, подключенном к сети, указав его имя в аргументе имя_сервера функции CreateObject. Это имя совпадает с частью имени компьютера в имени общей папки; для общей папки с именем «MyServerPublic» имя сервера имеет значение «MyServer».
[!NOTE] > Refer to COM documentation (see _Microsoft Developer Network_) for additional information about making an application visible on a remote networked computer. You may have to add a registry key for your application.—>
Следующий код возвращает номер версии экземпляра приложения Excel, запущенного на удаленном компьютере с именем MyServer :
Если удаленный сервер не существует или недоступен, возникает ошибка во время выполнения.
Используйте функцию CreateObject, если текущий экземпляр объекта отсутствует. Если экземпляр объекта уже запущен, запускается новый экземпляр и создается объект указанного типа. Для использования текущего экземпляра или запуска приложения с одновременной загрузкой файла используйте функцию GetObject.
Если объект зарегистрировал себя как объект типа «единственный экземпляр», создается только один экземпляр этого объекта независимо от того, сколько раз выполнялась функция CreateObject.
Пример
В этом примере функция CreateObject используется для создания ссылки ( xlApp ) на Microsoft Excel. Эта ссылка используется для доступа к свойству Visible Microsoft Excel, а затем используется метод Quit Microsoft Excel, чтобы закрыть это приложение. В конце ссылка освобождается.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA Objects
In this Article
Excel VBA objects refer to single “entities” made up of code and data. The Excel application itself is an object, as are workbooks, worksheets, cell ranges, and shapes. Every object has associated properties, and methods. Objects can also contain other objects and the collections object is used to refer to a group of the same Excel objects.
In this tutorial, we are going to look at some commonly used Excel Objects.
Application Object
The Application Object refers to the entire Excel application. The Application object contains the workbook object.
The following code uses the WindowState property of the Application object to set the Excel window to the maximum size available:
Workbooks Object
The Workbooks object refers to the collection of all the currently open Excel workbooks.
The following code uses the Workbooks.Add method to create a new workbook and add it to the collection:
You can access an individual workbook in the Workbooks collection through its index number or name. So you could refer to a Workbook called ExcelWb, by using Workbooks(“ExcelWB”).
Workbook Object
The workbook object is part of the Workbooks collection. The workbook object contains the worksheets collection (worksheets) and the sheets collection (worksheets, chart sheets, and macrosheets). The ActiveWorkbook object refers to the workbook that is active.
The following code uses the ActiveWorkbook.Save method to save the current active workbook:
Sheets Object
The sheets object refers to the collection of all the worksheets, chart sheets and macrosheets in a workbook. The following code uses the Sheets.Add method to add a new worksheet called ExtraSheet, after the last worksheet in the workbook:
Note the syntax of the Sheets.Add method is:
Sheets.Add(Before, After, Count, Type) where:
-Before is optional and specifies that the new sheet should be added before an existing sheet.
-After is optional and specifies that the new sheet should be added after an existing sheet.
-Count is optional and specifies the number of sheets to add.
-Type is optional and specifies the sheet type. xlWorksheet would add a new worksheet, xlChart would add a new chart sheet, and xlExcel4MacroSheet or xlExcel4IntlMacroSheet would add a new macrosheet. If blank the default xlWorksheet is used.
You can access an individual sheet in the Sheets collection through its index number or name. So you could refer to a Worksheet called SheetOne, by using Sheets(“SheetOne”).
Worksheets Object
The Worksheets object refers to the collection of all the worksheets in a workbook. The following code uses the Worksheets.Add method to add a new worksheet:
You can access an individual sheet in the Worksheets collection through its index number or name. So you could refer to a Worksheet called SheetTwo, by using Worksheets(“SheetTwo”).
Worksheet Object
The worksheet object is part of the Worksheets collection. The worksheet object contains the range object and other objects. The ActiveSheet object refers to the sheet that is active.
The following code changes the page orientation of the active sheet to landscape:
Note the Sheet object contains the PageSetup object and its orientation property is set to xlLandscape.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Range Object
The Range object can refer to a single cell or a set of cells in a worksheet. The following code shows you how to use the Range.Select method to select cells A1:B1:
Shapes Object
The Shapes object refers to the collection of all the shapes in a worksheet. The following code would select all the shapes on the ActiveSheet:
Shape Object
The Shape Object is part of the Shapes collection. The following code would create a rounded rectangle shape and then set the name property of the shape object:
Excel VBA Object Model
Excel’s VBA Object model describes the hierarchy of all the objects you can use in Excel. For example, you can use the Workbooks object to refer to all the other objects indirectly or directly. The following code shows you how to select cell A1, using the hierarchical structure:
Declaring and Assigning an Object Variable
You can declare and assign an object to a variable by using the Dim and Set keywords.
The following code shows you how to declare and assign a Range object to a variable:
It’s essential to understand how objects work to master VBA. You can learn more with our Interactive VBA Tutorial.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Как работать с Excel через VBA или объектная модель Excel
Объектная модель Excel
Перед созданием своей первой программы в Excel необходимо разобраться в объектную модели приложения. Имея четкое понимания об объектной модели Excel вы сможете управлять практически всеми объектами, создавать/изменять листы, графики, отдельные файлы и многое другое. Возможно на первый взгляд она покажется довольно сложной, но не пугайтесь на конкретных примерах у вас сложится целостная картина.
Структура объектов
Проще всего рассматривать объектную модель как некое дерево или иерархическую структуру, так как каждый объект имеет свое ответвление. Кусочек этой структуры вы можете увидеть на рисунке далее.
Самый главный объект, вершина нашей структуры, это собственно само приложение Excel — объект Application. Какие объекты входят в Excel? правильно книги (файлы Excel), поэтому в объекте Application содержится коллекция из книг — объект Workbooks. Из чего состоят книги — из листов, диаграмм, соответственно внутри объекта Workbooks мы видим объект Worksheets и Charts. Идем дальше, лист в свою очередь состоит из строк, столбцов, ячеек это объекты Rows, Columns, Range.
Это, конечно, как вы понимаете только часть объектной модели Excel, мы перечислили только одни их самых основных объектов. Полное дерево объектов исчисляется сотнями объектов. Возможно она сейчас кажется сложной, не переживайте со временем вы начнете быстро в ней ориентироваться. Главное сейчас — это понять, что есть некие объекты, которые могут состоять из других объектов.
Объекты и коллекции объектов
Многие объекты, которые мы перечислили выше являются коллекциями. Коллекция — это группа однотипных объектов (или классов). Например Workbook s — это коллекция всех открытых в данный момент книг (объектов Workbook). А коллекция Worksheet s состоит из листов книги (объектов Worksheet), и так далее. Как правило все коллекции заканчиваются буквой S.
Давайте посмотрим, как обращаться к конкретным элементам коллекции в коде VBA.
Мы можем указать порядковый номер (начиная с единицы) элемента в коллекции. Worksheets(3) — в этом случае мы обращаемся к 3-му листу книги.
Мы также можем указать название листа в кавычках Worksheets(«Название листа»).
Аналогичным образом можно обратиться к конкретной книге Workbook(«Названием книги»).
Чтобы обратиться к объекту Excel (к листу, или ячейке) необходимо указать ссылку на этот объект, перечислив полный путь к нему в соответствии с объектной моделью.
Например, для ячейки A1 полная ссылка будет выглядеть следующим образом:
На самом деле полный путь писать не обязательно. Application — можно практически всегда не указывать. Workbooks(«Название книги») — можно не указывать, если необходимо обратиться к ячейке из активной книги, а Worksheets(«Название листа») можно не писать в случае если код должен выполнять действия на активном листе. Т.е. в можно упростить до:
Но всегда имейте ввиду, что это будет ячейка на активном листе.
Свойства объектов
Все объекты имеют свойства и методы. Например, объект Range (диапазон ячеек) имеет свойство Value, в котором содержится значение.
Вы можете получать значения из свойств объекта, просто указав путь к нужному свойству. Следующий код выведет значение ячейки A1 на активном листе.
А следующий код присвоит свойству Value новое значение 12345.
Протестируйте эти функции в своем файле.
Кстати, есть свойства объектов, которые доступны только для чтения. Т.е. вы сможете только получить значения этих свойств, но не сможете присвоить им другие значения. Например, свойство Range(«A1»).Address которое содержит адрес ячейки. При попытке записать новое значение в такое свойство будет возникать ошибка.
Или же свойство Worksheets.Count — вы можете только получить количество листов, но не можете изменить количество листов, задав новое свойство Count. Для этого существуют методы объектов.
Методы объектов
В отличие от свойств, которые просто сохраняют или передают значение, методы выполняют какие-либо действия с объектом. Например метод Worksheets.Add создает новый пустой лист в книге. Еще один пример это метод Clear, который позволяет очистить содержимое ячеек. Следующий код очистит данные и форматы из диапазона ячеек A1:C10.
Есть аналогичная функция, которая не удаляет при этом форматирование ячеек, а только очищает их от значений
Методы могут иметь дополнительные аргументы. Например, метод AddComment имеет обязательный аргумент Text, в котором необходимо передать текст комментария к ячейке.
Также можно использовать следующий код для вызова методов. Возможно это более привычная запись, когда по аналогией с функцией Excel мы в скобках передаем аргументы этой функции.
Приемы и лайфхаки
Автоматическое заполнение кода по начальным символам
Часто, особенно на первых порах, вы не запомните точное название всех объектов, но будете помнить их первые символы. В редакторе кода вы можете использовать отобразить список названий и автоматически записать объект по первым символам. Для этого используйте сочетание клавиш Ctrl+ J и увидите список из предложенных вариантов.
Просмотр свойств и методов у объекта
Когда вы будете писать свои программы, то редактор кода VBE будет подсказывать список свойств и методов у объекта. Чтобы отобразить этот список достаточно ввести объект, например, Worksheets и поставить точку, отобразится список свойств и методов. Выберите нужный с помощью мышки или же используйте стрелки. Вы также можете начать писать название свойства и редактор кода подберет подходящее. Когда выбор сделан — нажимайте клавишу Tab.
Явно указывайте тип переменных
Предыдущий лайфхак не будет работать для созданных локальных переменных до тех пор, пока вы явно не укажите их тип. Например, если вы захотели создать переменную MySheet в которой хотите хранить текущий лист. То список свойств и методов у такой переменной вы не увидите. Но стоит добавить строчку кода и явно указать тип переменной:
И подсказки снова заработают.
Быстрый просмотр справки
Все свойства и методы знать невозможно, так как их тысячи. Первое время вы будете активно пользоваться справкой. Советую использовать официальную справку на сайте Microsoft.
Чтобы быстро посмотреть информацию по интересующему вас объекту, свойству или методу просто поставьте курсор на интересующий элемент кода и нажмите клавишу F1. В окне браузера откроется официальная справка по этому элементу.
Поиск по объектной модели
Также вначале пути у вас постоянно будут возникать вопрос «А как называется свойство, которое отвечает за. «. Иногда мы и не заем есть ли такое свойство/метод вообще. Хороший вариант изучения — просмотр объектной модели. Переходите в редактор кода VBA и нажимайте клавишу F2. Откроется окно с поиском по объектной модели. Тут вы найдете все имеющиеся свойства, методы, события и прочие элементы в модели. Просматривайте их, как правило в названии элемента заложена его суть и вы найдете то что искали. А в процессе поиска будете запоминать и другие элементы, которые будут попадаться на глаза.
Давайте разберем на примере. Допустим нам надо защитить лист, но мы не знаем как точно зазывается свойство или метод.
- Открываем объектную модель клавишей F2.
- Так как мы хотим защитить лист, то логично предположить, что это метод в объекте Worksheet. Введем его в строку поиска и нажмем бинокль.
- В результатах поиска выбираем наш объект Worksheet и просматриваем его элементы.
- Находим метод Protect (Защита).
- Мы также можем просмотреть описание всех аргументов этого метода
- Конечно если что-то не понятно, то жмем клавишу F1 и открываем справку по этому методу с подробным описанием каждого аргумента.
На этом данную статью завершим, а в следующих мы более подробно поговорим про самый распространенный объект Excel — объект Range.
Источник
“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.)
If you’ve read any of the other macro or VBA tutorials in Power Spreadsheets, you’ve probably noticed that some terms keep popping up over and over.
One of the concepts that keep coming up, and will continue to come up in future tutorials, is that of objects. The main reason for this is simple:
VBA is (loosely) based on Object Oriented Programming. At a basic level, this (roughly) means that the VBA paradigm mostly relies on working with (or manipulates) objects.
As a consequence of the above, if you want to really master Excel macros and Visual Basic for Applications, you must have a good understanding of the following 3 topics:
- Objects.
- How to manipulate VBA objects.
- Excel’s VBA object model.
My 2 main purposes when writing this VBA tutorial are to:
- Explain the main characteristics of Excel’s VBA object model.
- Illustrate how you construct VBA object references when working with Visual Basic for Applications. This allows you to identify the Excel VBA object you want to work with and manipulate.
More precisely, in this macro tutorial I explain the following topics:
I’ll say from the start that the topics of Excel’s VBA object model and building VBA object references are not particularly simple. However…
Your knowledge and understanding of Excel’s VBA object model and object references will improve as you continue to study, and work with, Visual Basic for Applications. Therefore, don’t worry if, after reading this VBA tutorial things are not absolutely clear. This guide should provide you with a solid base and, with some work I’m sure you’ll master this topic and know all you need about Excel VBA objects.
Let’s begin by answering the first question that you probably have regarding the introduction I’ve made above by understanding…
Why Excel’s VBA Object Model Is Important
Visual Basic for Applications is included in most products that are part of Microsoft Office. In addition to Excel, the list of applications that have VBA includes PowerPoint, Word and Access.
This underscores one of the great advantaged of learning VBA:
Once you know Visual Basic for Applications, you can immediately start writing macros for the other products that use VBA. In fact, you’ll be able to create macros that work across all of those different applications.
One of the main topics you need to master in order to reach those levels of expertise is objects. At a basic level, VBA manipulates objects.
Each individual Application that works with VBA (for example, Excel, Word, PowerPoint, Outlook) has its own unique object model. Having a good understanding of the principles behind objects and object models helps you work with VBA in these different Applications.
OK. So Excel’s VBA object model is clearly important. The next question you may have is…
What Is Excel’s VBA Object Model
At a basic level, the Excel VBA Object Model is a hierarchy of the objects you can use when working with Excel VBA.
Among other advantages, this hierarchy makes VBA objects easier to reference. Therefore, let’s take a closer look at…
Excel’s VBA Object Hierarchy
An object hierarchy looks as follows:
- Level #1: At the very top, you have one single object.
- Level #2: The object at the top of the hierarchy contains some objects.
- Level #3: In turn, the object in the second level of the hierarchy, may contain other objects.
- Level #4: The objects in level 3 may contain other objects.
- …
- You probably get the idea… Objects may contain other objects. The process repeats itself until you reach objects that don’t contain any other objects.
When you’re working with a particular software application, the first object to consider is the application itself (the Application object). Generally, the application is at the top of the hierarchy.
In the case of Excel, the Application object is Excel itself.
Since Visual Basic for Applications can communicate with other applications and programs beyond Excel, this isn’t strictly speaking the top level of the hierarchy. However, you’ll usually see most people referring to the Application object itself as being the top of Excel’s VBA object hierarchy. That’s the convention I use in this macro tutorial.
The Application object contains other VBA objects. Some of the VBA objects contained by the Excel Application object are the following:
- Add-Ins, which contains all Add-In objects.
- Windows, which (at this level) contains all Window objects in the application.
- Workbooks, which contains all Workbook objects.
Each of these VBA objects, in turn, is capable of containing other objects. For example, some of the VBA objects that can be contained within a Workbook object are the following:
- Charts, which contains Chart objects.
- Names, which contains Name objects.
- VBProjects, which represents open projects.
- Windows, which (at this level) contains Window objects in the specified Excel workbook.
- Worksheets, which contains Worksheet objects.
Again, these VBA objects can contain other objects. Continuing with the example above, a Worksheet object can contain the following VBA objects:
- ChartObjects, which contains ChartObject objects.
- Comment, which represents a cell comment.
- Hyperlink, which represents a hyperlink.
- Name, which represents a defined name for a particular cell range.
- PageSetup, which is used to store printing information.
- PivotTables, which contains PivotTable objects.
- Range, which represents cells, rows, columns, selections of cells with contiguous blocks of cells, or 3-D ranges.
- As I explain here, the Range object is one of the most important (and most frequently used) objects.
Graphically, the portion of Excel’s VBA object hierarchy described above looks roughly as follows:
The image above illustrates only a very small portion of Excel’s VBA object hierarchy. The Excel Object Model has a very large number of objects. A full diagram of Excel’s VBA object hierarchy exceeds the scope of this Excel VBA Object Model Tutorial.
What can you do about this?
You can definitely master Visual Basic for Applications despite the huge amount of Excel VBA objects. There are several reasons for this, including the following:
- In practice, you’ll usually deal with a limited amount of VBA objects. There are some objects that you’re unlikely to ever need (or will very rarely need).
- If you’re stuck when working on a particular problem, you can use certain strategies for purposes of finding out which Excel VBA objects to use. You can, for example, use the macro recorder to discover VBA objects.
Additionally, as you continue working with Visual Basic for Applications, you’ll start noticing the logic behind the structure of the Excel VBA object hierarchy.
Object Collections
Collections are defined by 2 main characteristics:
- They are themselves objects.
- Their main purpose is to group and manage VBA objects of the same class.
In other words, collections are VBA objects that are used to group and manage other objects (which are related).
The fact you can group and manage several VBA objects by using collections is extremely useful in some situations. Imagine, for example, that you want to do something with or to a particular group of objects. If all of these objects are part of the same collection, you can structure your VBA code to go through each of the members of the collection and carry out the desired actions. As you can imagine, this structure is simpler than, for example, having to list each of the collection members individually.
In other words, collections allow you to work with a complete group of VBA objects at the same time, instead of working with each single object.
The following are examples of common collections:
- Workbooks, which is a collection of all the Excel workbooks that are currently open.
- Worksheets, the collection of all the Excel worksheets within a particular Workbook.
- Charts, which groups all chart sheets that are inside a particular Workbook.
- Sheets, which is a collection of all the sheets within a particular Workbook. In this case, it doesn’t matter the type of sheet. Therefore, this collection includes both worksheets and charts sheets.
In fact, if you go back up to the explanation of Excel’s VBA object hierarchy, you’ll find several other examples of collections. Basically, any VBA object which is listed there as containing other objects is a collection.
By now you probably have a firm grasp of what an object and a collection are. So let’s get into the actual practice. Let’s look at how you can start referencing VBA objects with Visual Basic for Applications:
Introduction To VBA Object References
Knowing how to refer to objects when writing VBA code is essential. The reason for this is that, obviously, when you want to start working with a particular VBA object, you must identify it.
The question is, how do you do it? How do you refer to an object in Visual Basic for Applications?
Let’s take a look at some of the most common and basic situations. The purpose of this section is to serve as an introduction to VBA object references. There are many other more advanced cases. For example, I explain several ways to refer to VBA’s Range object in Excel VBA Object Model And Object References: The Essential Guide which you can find in the Archives.
Object References: Fully Qualified References And Connecting VBA Objects
Let’s start by taking a look at how to refer to an object by going through the whole hierarchy of Excel VBA objects. This is known as a fully qualified reference because you tell Excel exactly what VBA object you want to work with by referencing all of its parents.
As I explain in the following sections, you can usually simplify fully qualified references. However, you must learn how fully qualified references work. They are the basis of VBA object references and, in practice, you’ll use them most of the time. Additionally, they’re quite useful for purposes of understanding better the VBA code behind your macros.
You already know that the object at the top of the Excel VBA object hierarchy is Application. Referring to this object is very easy. In the Visual Basic Editor, you refer to Application by typing:
Application
From there on, you need to start moving along the hierarchy by using the dot (.) operator. In other words, you connect each VBA object to the previous one (the object parent) by using a dot (.). Those dots (.) are used to connect and reference members of Excel’s VBA object model from the top down.
To see this in practice, let’s go back to the example of the Excel VBA object hierarchy that I display above. Assume that you want to refer to a Range object. As shown in the graph displayed below, this object is at the bottom of the pyramid used in the example. There are 2 VBA objects and 3 steps between the Application and the Range object, as shown by the image below:
You already know that you simply need to connect the different objects with a dot (.) while you’re going down the Excel VBA object hierarchy. In other words, you know that, in very general terms, you can refer to a Range object using the following basic structure:
Application.Workbooks.Worksheets.Range
Graphically:
Easy, right?
This is, however, just a basic framework. You’ll notice that this very basic structure is not actually identifying an individual VBA object. You may be wondering:
- If there are several workbooks or worksheets how does Excel know to which one I’m referring to?
- How does Excel know what is the range I want to work with?
These questions can be summarized by the following:
How do you refer to a particular object within a collection?
Let’s answer this question so that you can complete the fully qualified reference above.
VBA Object References: An Object From A Collection
It is likely that, most of the time, you’ll be working with a particular VBA object from a collection. This is in contrast with the collection as a whole.
Note that you can also work with a collection as a whole. In fact, the ability to do this is one of the advantages of collections.
However, let’s focus for now on how you can reference an object from a collection. For these purposes, you can use either of the following 2 options:
Option #1: Using The VBA Object Name.
In this case, the syntax that you must use to refer to an object is “Collection_name(“Object_name”)”. In other words:
- #1: The name of the relevant collection (collection_name) goes first.
- #2: Collection_name is followed by parentheses ().
- #3: Within the parentheses, you have the name of the individual VBA object (Object_name).
- #4: The VBA object name is within quotations (“”).
- If you fail to include the quotation marks, Excel understands that the VBA object name is a variable name. Therefore, it won’t be able to identify the object you want.
- In other words, don’t forget the quotations when using this VBA object reference method.
For example, if you’re working with an Excel Workbook that has 3 worksheets and you want to work with Sheet1, you can use either of the following:
Worksheets("Sheet1")
or
Sheets("Sheet1")
Option #2: Using Index Number.
If you choose to use this option, you refer to a VBA object using “Collection_name(Index_number)”. This structure is substantially the same as that above with the following 2 differences:
- Instead of using the VBA object name, you refer to it by using its index number.
- You don’t use double quotes within the parentheses, just a number.
Going back to the example above, where you’re want to work with Sheet1, you can use either of the following 2 options:
Worksheets(1)
or
Sheets(1)
Now that you know how to refer to an individual VBA object within a collection, let’s go back to the fully qualified reference that I used as an example in the section above:
Application.Workbooks.Worksheets.Range
How can you complete this, assuming that the object you want to work with is cell A1 from Worksheet Sheet1 within Workbook Book1?
If you’re using the object name to refer to each of the individual VBA objects (option #1 above), the fully qualified reference for this cell is:
Application.Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1")
As you may guess, if you had to reference each and every single object using a fully qualified reference, your VBA code would get quite long very fast. From a typing perspective, this may get a little bit annoying. Additionally, and perhaps more importantly, these very long pieces of VBA code can be difficult to read.
There are some ways in which you can simplify object references, making the VBA code much shorter. Let’s take a look at some of the methods that you can apply for these purposes…
Simplifying Fully Qualified Object References
The ability to simplify a VBA object reference has several advantages. Mainly, this allows you to shorten your VBA code and make it easier to read.
The main reason why you can simplify fully qualified object references is because Excel’s VBA object model has some default objects. These default objects are assumed by Excel unless you enter something different. This leads me to a very important point, which is that…
Simplifying fully qualified object references is not without dangers. In particular, the second simplification method described below relies on you correctly identifying the current active Workbook and Worksheet. If you make a mistake by for example, thinking that the current active Worksheet is Sheet1 when in reality its Sheet2, you’ll face problems. The most likely issues you’ll encounter in these cases are:
- Excel returns an error.
- Excel returns an erroneous result.
- Excel executes an erroneous action that you can’t undo.
Another possible disadvantage of simplifying fully qualified object references is related to execution speed. This happens, for example, if you’re working with a particular macro that works with several Excel worksheets. In that case, you have to go through all of them to activate them. Needless to say, this isn’t very efficient.
Considering the above, ensure that you’re only using these simplification methods when appropriate. Perhaps more importantly, remember that you shouldn’t blindly simplify fully qualified references all the time.
In fact, you should probably (as a general rule):
- Fully qualify VBA object references; and
- Avoid relying on default objects, with a few exceptions.
- One of these main exceptions, as I explain below, is relying on the Application default object. This particular VBA object is seldom included in VBA code, although there are some cases in which you must reference the Application.
In other words, having a deep knowledge of Excel’s VBA object model and using fully qualified references has 2 main advantages:
- Reliability.
- Accuracy.
An alternative to the extremes of fully qualifying references or simplifying them is using With… End With statements. These statements simplify macro syntax by executing several statements which refer to the same VBA object. At the same time, due to their structure, they allow you to maintain fully qualified object references.
You can see a very simple example of a With…End With statement in this macro that deletes rows based on whether a cell in a given range is blank.
With the warning above in mind, let’s take a look at the methods you can use to simplify fully qualified object references:
Simplification #1: The Application Object.
The main default VBA object is the Application object. As a general rule:
- This object is always assumed; and
- It doesn’t matter where the VBA code is located.
When creating macros, it is assumed that you’ll be working with Excel. In other words, Excel assumes that you’re working with the Application object. Therefore, as you may expect, you can generally omit this Excel VBA object from your object references.
Explicitly referring to (entering) the Application object makes sense in only a few cases.
Applying this shortcut to the statement referring to cell A1 in Sheet1 within Book1 that has been used as an example simplifies the reference as follows:
Workbooks("Book1.xlsx").Worksheets("Sheet1").Range("A1")
Simplification #2: The Active Workbook and Worksheet.
The second group of default objects you can use to simplify fully qualified object references applies when you’re working inside a standard module. Within the Visual Basic Editor, you can usually find standard modules in the Project Window under the Modules node:
In these cases, in addition to assuming that you’re working with the Application object, Excel also assumes that you’re working with the active Workbook.
Therefore, if you know that the current active Excel workbook is the Workbook you want to work with, you can omit that part of the VBA object reference. Continuing with the example above, the statement can then be shortened to the following:
Worksheets("Sheet1").Range("A1")
Finally, if you’re sure that the Excel worksheet you want to work with is the current active Worksheet, you can also omit that part of the VBA object reference. The statement above can then be shortened even further:
Range("A1")
In addition to the dangers of using this simplification that I explain at the beginning of this section, there is a further aspect you must consider. The 2 assumptions that I’ve listed in Simplification #2 above only work as long as you’re in a standard module. Therefore, you must avoid relying on these assumptions when working in another type of module. For example:
Conclusion
Excel’s VBA object model is extremely important. You can’t ignore this topic if you really want to become a master in Excel macros and Visual Basic for Applications.
Excel’s VBA object model is not the simplest topic to understand but, if you practice and study, you’ll eventually master the topic. Then, you’ll be on your way to creating powerful macros that increase your productivity and efficiency when working with Excel.
If you’ve studied this particular VBA tutorial, you not only have a good understanding of what is Excel’s VBA object model, but also know how to start building object references in Visual Basic for Applications. This ability to create appropriate VBA object references is what allows you to tell Excel which object you want to work with and manipulate. This is an essential skill that you now have in your VBA knowledge-box.
Due to the complexity and extensiveness of Excel’s VBA object model, this is a topic that we’re all constantly studying and learning about.
VBA Object
In Microsoft Excel, a VBA Object can contain one or more than one object. Such as a single workbook can have one or more than one worksheet. Workbook, Worksheet, Range, and cells are the objects in Excel. Each object has its own properties. And they all have a different method of application. Let say the workbook is the main object which has 2 worksheets in it. Those 2 worksheets will be its child object. One of the sheets has one range, so that sheet will become the main object, and the range will be its child object.
How to Use Object in VBA
Let’s see the examples of object in Excel VBA.
You can download this VBA Object Excel Template here – VBA Object Excel Template
Example #1 – VBA Object
It can be written in many ways. Suppose we need to print any text in a cell, so this can be done in various ways. We can directly use the range value to that cell. This direct method is not a part of VBA Object but a process of performing a task that could be done by VBA Object as well. For this:
Step 1: Go to VBA and insert a Module from the Insert menu option as shown below.
Step 2: Now write the Sub Category of performed function, like VBA Object, in any other name as per your choice, as shown below.
Code:
Sub VBAObject2() End Sub
Step 3: Now select the range function considering any cell, let’s say cell B3 with Value as shown below.
Code:
Sub VBAObject2() Range("B3").Value = End Sub
Step 4: Now add text or word in that range cell as shown below.
Code:
Sub VBAObject2() Range("B3").Value = "VBA Object" End Sub
Step 5: Now, compile the code and run it by pressing the play button located below the menu bar.
Example #2 – VBA Object
This is the normal way of printing text to any cell. How we will see how the same process can be done when we use VBA Object. For this, we will need another fresh module. And in that,
Step 1: Go to VBA and insert a Module from the Insert menu option as shown below.
Step 2: Write the Sub Category of VBA Object as shown below.
Code:
Sub VBAObject1() End Sub
Step 3: Here, we will see the complete VBA Object from the main to a child category. First, select the currently opened workbook with the help of the command ThisWorkBook with Application, as shown below. This will select the workbook which is actually opened and last selected.
Code:
Sub VBAObject1() Application.ThisWorkbook End Sub
Step 4: Now select the sheet which is currently opened in the workbook, or we can write the name of the worksheet as well. Here, we have written the name of sheet Sheet1 in inverted commas, as shown below.
Code:
Sub VBAObject1() Application.ThisWorkbook.Sheets ("Sheet1") End Sub
Step 5: Now comes the range. Select the range of the cell where we need to print or insert the text. Here we are selecting cell B4, as shown below.
Code:
Sub VBAObject1() Application.ThisWorkbook.Sheets("Sheet1").Range("B4").Value End Sub
Step 6: At last, add the text which we need to see in the select Range cell as shown below.
Code:
Sub VBAObject1() Application.ThisWorkbook.Sheets("Sheet1").Range("B4").Value = "VBA Object" End Sub
Step 7: Now, compile and run the code. We will see cell B4 has the text “VBA Object”.
This complete process is called VBA Object. In which we have first selected the main object, i.e. Workbook, which has its child object, i.e. Sheet1, and that has another child object range, i.e. cell B4.
Example #3 – VBA Object
There are many different ways to add text to any cell. One can be with Excel VBA Object, and others can be without it. In these categories, again, there are many ways to do it. Let’s see another way to add VBA Object. For this, we will need a module.
Step 1: In that module, add a subcategory; better make it with sequence number as shown below.
Code:
Sub VBAObject3() End Sub
Step 2: Select the worksheet by adding the name of the current worksheet, which is Sheet1, as shown below.
Code:
Sub VBAObject3() Worksheets("Sheet1"). End Sub
Step 3: Now, add the range of the cell where we want to see the output, as shown below.
Code:
Sub VBAObject3() Worksheets("Sheet1").Range("A3").Value End Sub
Step 4: At last, give it a value that we can see once we run the code. We are considering the same text as seen in example 1.
Code:
Sub VBAObject3() Worksheets("Sheet1").Range("A3").Value = "VBA Object" End Sub
Step 5: Now run the code. We will see; cell A3 got the text which we wanted to add there, as shown below.
In this process, we have directly added the worksheet. So Worksheet will become our Object, and Range will become its child object.
Step 6: There is another way to perform the same task. In the bracket of the worksheet, instead of writing the sheet name, we can write the sequence of the sheet, which is 1, as shown below.
Code:
Sub VBAObject3() 'Worksheets("Sheet1").Range("A3").Value = "VBA Object" Worksheets(1).Range("B3").Value = "VBA Object" End Sub
Step 7: Now run the modified code. We will see cell B3 got the same text VBA Object as cell A3, as shown below.
By keeping both the code in line, we can see and compare the changes we made. In another way,
Step 8: Instead of the Worksheet function, if we use the Sheet with sequence and selecting cell C3 as range as shown below.
Code:
Sub VBAObject3() 'Worksheets("Sheet1").Range("A3").Value = "VBA Object" 'Worksheets(1).Range("B3").Value = "VBA Object" Sheet1.Range("C3").Value = "VBA Object" End Sub
Step 9: Now run this code. We will see, again the same text will get added in range cell C3.
In all the methods which we have seen in this example, Worksheet is our object, and the range of the cell is child object or Sub-object.
Pros and Cons of Excel VBA Object
- We can make as many objects and link them together to sink them.
- It makes use of Workbook, Sheet, and Range easy.
- This allows a user to make changes in a specific Workbook, Worksheet or Range.
- The same process can be performed by a much shorter code with having the same result.
Things to Remember
- Worksheet and Sheet both have the same use.
- We can select any worksheet of the same workbook of any number sequence.
- While writing big lines of code, it is important to form an Object in which the Workbook, Worksheets, and Ranges of different cells are linked.
- Must save the file in Macro-Enabled Excel format. It allows us to use the code and change the code whenever required.
Recommended Articles
This is a guide to VBA Object. Here we discuss how to use Object in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA IsNumeric
- VBA UCASE
- VBA Object Required
- VBA ByVal
In this Article
- Application Object
- Workbooks Object
- Workbook Object
- Sheets Object
- Worksheets Object
- Worksheet Object
- Range Object
- Shapes Object
- Shape Object
- Excel VBA Object Model
- Declaring and Assigning an Object Variable
Excel VBA objects refer to single “entities” made up of code and data. The Excel application itself is an object, as are workbooks, worksheets, cell ranges, and shapes. Every object has associated properties, and methods. Objects can also contain other objects and the collections object is used to refer to a group of the same Excel objects.
In this tutorial, we are going to look at some commonly used Excel Objects.
Application Object
The Application Object refers to the entire Excel application. The Application object contains the workbook object.
The following code uses the WindowState property of the Application object to set the Excel window to the maximum size available:
Sub MaximizingTheExcelWindow()
Application.WindowState = xlMaximized
End Sub
Workbooks Object
The Workbooks object refers to the collection of all the currently open Excel workbooks.
The following code uses the Workbooks.Add method to create a new workbook and add it to the collection:
Sub AddingANewWorkbookToTheWorkbooksCollection()
Workbooks.Add
End Sub
You can access an individual workbook in the Workbooks collection through its index number or name. So you could refer to a Workbook called ExcelWb, by using Workbooks(“ExcelWB”).
Workbook Object
The workbook object is part of the Workbooks collection. The workbook object contains the worksheets collection (worksheets) and the sheets collection (worksheets, chart sheets, and macrosheets). The ActiveWorkbook object refers to the workbook that is active.
The following code uses the ActiveWorkbook.Save method to save the current active workbook:
Sub SavingTheWorkbook()
ActiveWorkbook.Save
End Sub
Sheets Object
The sheets object refers to the collection of all the worksheets, chart sheets and macrosheets in a workbook. The following code uses the Sheets.Add method to add a new worksheet called ExtraSheet, after the last worksheet in the workbook:
Sub AddingANewSheet()
ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Worksheets(Worksheets.Count), Count:=1, _
Type:=xlWorksheet).Name = "ExtraSheet"
End Sub
Note the syntax of the Sheets.Add method is:
Sheets.Add(Before, After, Count, Type) where:
-Before is optional and specifies that the new sheet should be added before an existing sheet.
-After is optional and specifies that the new sheet should be added after an existing sheet.
-Count is optional and specifies the number of sheets to add.
-Type is optional and specifies the sheet type. xlWorksheet would add a new worksheet, xlChart would add a new chart sheet, and xlExcel4MacroSheet or xlExcel4IntlMacroSheet would add a new macrosheet. If blank the default xlWorksheet is used.
You can access an individual sheet in the Sheets collection through its index number or name. So you could refer to a Worksheet called SheetOne, by using Sheets(“SheetOne”).
Worksheets Object
The Worksheets object refers to the collection of all the worksheets in a workbook. The following code uses the Worksheets.Add method to add a new worksheet:
Sub AddingANewSheet()
Worksheets.Add
End Sub
You can access an individual sheet in the Worksheets collection through its index number or name. So you could refer to a Worksheet called SheetTwo, by using Worksheets(“SheetTwo”).
Worksheet Object
The worksheet object is part of the Worksheets collection. The worksheet object contains the range object and other objects. The ActiveSheet object refers to the sheet that is active.
The following code changes the page orientation of the active sheet to landscape:
Sub ChangingOrientationToLandscape()
ActiveSheet.PageSetup.Orientation = xlLandscape
End Sub
Note the Sheet object contains the PageSetup object and its orientation property is set to xlLandscape.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Range Object
The Range object can refer to a single cell or a set of cells in a worksheet. The following code shows you how to use the Range.Select method to select cells A1:B1:
Sub SelectingARange()
Range("A1:B1").Select
End Sub
Shapes Object
The Shapes object refers to the collection of all the shapes in a worksheet. The following code would select all the shapes on the ActiveSheet:
Sub SelectingAllTheShapes()
ActiveSheet.Shapes.SelectAll
End Sub
Shape Object
The Shape Object is part of the Shapes collection. The following code would create a rounded rectangle shape and then set the name property of the shape object:
Sub UsingTheShapeObject()
With Worksheets(1).Shapes.AddShape(msoShapeRoundedRectangle, _
200, 100, 80, 80)
.Name = "A Rounded Rectangle"
End With
End Sub
VBA Programming | Code Generator does work for you!
Excel VBA Object Model
Excel’s VBA Object model describes the hierarchy of all the objects you can use in Excel. For example, you can use the Workbooks object to refer to all the other objects indirectly or directly. The following code shows you how to select cell A1, using the hierarchical structure:
Sub UsingTheHierachicalStructure()
Workbooks("Book1").Worksheets("Sheet1").Range("A1").Select
End Sub
Declaring and Assigning an Object Variable
You can declare and assign an object to a variable by using the Dim and Set keywords.
For example:
Dim ws as worksheet
Set ws = ActiveWorkbook.ActiveSheet
The following code shows you how to declare and assign a Range object to a variable:
Sub AssigningARangeToAVariable()
Dim rngOne As Object
Set rngOne = Range("A1:C1")
rngOne.Font.Bold = True
With rngOne
.Font.Bold = True
.Font.Name = "Calibri"
.Font.Size = 9
.Font.Color = RGB(35, 78, 125)
.Interior.Color = RGB(205, 224, 180)
.Borders(xlEdgeBottom).LineStyle = xlContinuous
End With
End Sub
The result is:
It’s essential to understand how objects work to master VBA. You can learn more with our Interactive VBA Tutorial.