Объекты vba excel список

Термин Объекты Excel (понимаемый в широком смысле, как объектная модель Excel) включает в себя элементы, из которых состоит любая рабочая книга Excel. Это, например, рабочие листы (Worksheets), строки (Rows), столбцы (Columns), диапазоны ячеек (Ranges) и сама рабочая книга Excel (Workbook) в том числе. Каждый объект Excel имеет набор свойств, которые являются его неотъемлемой частью.

Например, объект Worksheet (рабочий лист) имеет свойства Name (имя), Protection (защита), Visible (видимость), Scroll Area (область прокрутки) и так далее. Таким образом, если в процессе выполнения макроса требуется скрыть рабочий лист, то достаточно изменить свойство Visible этого листа.

В Excel VBA существует особый тип объектов – коллекция. Как можно догадаться из названия, коллекция ссылается на группу (или коллекцию) объектов Excel. Например, коллекция Rows – это объект, содержащий все строки рабочего листа.

Доступ ко всем основным объектам Excel может быть осуществлён (прямо или косвенно) через объект Workbooks, который является коллекцией всех открытых в данный момент рабочих книг. Каждая рабочая книга содержит объект Sheets – коллекция, которая включает в себя все рабочие листы и листы с диаграммами рабочей книги. Каждый объект Worksheet состоит из коллекции Rows – в неё входят все строки рабочего листа, и коллекции Columns – все столбцы рабочего листа, и так далее.

В следующей таблице перечислены некоторые наиболее часто используемые объекты Excel. Полный перечень объектов Excel VBA можно найти на сайте Microsoft Office Developer (на английском).

Объект Описание
Application Приложение Excel.
Workbooks Коллекция всех открытых в данный момент рабочих книг в текущем приложении Excel. Доступ к какой-то конкретной рабочей книге может быть осуществлён через объект Workbooks при помощи числового индекса рабочей книги или её имени, например, Workbooks(1) или Workbooks(«Книга1»).
Workbook Объект Workbook – это рабочая книга. Доступ к ней может быть выполнен через коллекцию Workbooks при помощи числового индекса или имени рабочей книги (см. выше). Для доступа к активной в данный момент рабочей книге можно использовать ActiveWorkbook.

Из объекта Workbook можно получить доступ к объекту Sheets, который является коллекцией всех листов рабочей книги (рабочие листы и диаграммы), а также к объекту Worksheets, который представляет из себя коллекцию всех рабочих листов книги Excel.

Sheets Объект Sheets– это коллекция всех листов рабочей книги. Это могут быть как рабочие листы, так и диаграммы на отдельном листе. Доступ к отдельному листу из коллекции Sheets можно получить при помощи числового индекса листа или его имени, например, Sheets(1) или Sheets(«Лист1»).
Worksheets Объект Worksheets – это коллекция всех рабочих листов в рабочей книге (то есть, все листы, кроме диаграмм на отдельном листе). Доступ к отдельному рабочему листу из коллекции Worksheets можно получить при помощи числового индекса рабочего листа или его имени, например, Worksheets(1) или Worksheets(«Лист1»).
Worksheet Объект Worksheet – это отдельный рабочий лист книги Excel. Доступ к нему можно получить при помощи числового индекса рабочего листа или его имени (см. выше).

Кроме этого Вы можете использовать ActiveSheet для доступа к активному в данный момент рабочему листу. Из объекта Worksheet можно получить доступ к объектам Rows и Columns, которые являются коллекцией объектов Range, ссылающихся на строки и столбцы рабочего листа. А также можно получить доступ к отдельной ячейке или к любому диапазону смежных ячеек на рабочем листе.

Rows Объект Rows – это коллекция всех строк рабочего листа. Объект Range, состоящий из отдельной строки рабочего листа, может быть доступен по номеру этой строки, например, Rows(1).
Columns Объект Columns – это коллекция всех столбцов рабочего листа. Объект Range, состоящий из отдельного столбца рабочего листа, может быть доступен по номеру этого столбца, например, Columns(1).
Range Объект Range – это любое количество смежных ячеек на рабочем листе. Это может быть одна ячейка или все ячейки листа.

Доступ к диапазону, состоящему из единственной ячейки, может быть осуществлён через объект Worksheet при помощи свойства Cells, например, Worksheet.Cells(1,1).

По-другому ссылку на диапазон можно записать, указав адреса начальной и конечной ячеек. Их можно записать через двоеточие или через запятую. Например, Worksheet.Range(«A1:B10») или Worksheet.Range(«A1», «B10») или Worksheet.Range(Cells(1,1), Cells(10,2)).

Обратите внимание, если в адресе Range вторая ячейка не указана (например, Worksheet.Range(«A1») или Worksheet.Range(Cells(1,1)), то будет выбран диапазон, состоящий из единственной ячейки.

Приведённая выше таблица показывает, как выполняется доступ к объектам Excel через родительские объекты. Например, ссылку на диапазон ячеек можно записать вот так:

Workbooks("Книга1").Worksheets("Лист1").Range("A1:B10")

Содержание

  1. Присваивание объекта переменной
  2. Активный объект
  3. Смена активного объекта
  4. Свойства объектов
  5. Методы объектов
  6. Рассмотрим несколько примеров
  7. Пример 1
  8. Пример 2
  9. Пример 3

Присваивание объекта переменной

В Excel VBA объект может быть присвоен переменной при помощи ключевого слова Set:

Dim DataWb As Workbook
Set DataWb = Workbooks("Книга1.xlsx")

Активный объект

В любой момент времени в Excel есть активный объект Workbook – это рабочая книга, открытая в этот момент. Точно так же существует активный объект Worksheet, активный объект Range и так далее.

Сослаться на активный объект Workbook или Sheet в коде VBA можно как на ActiveWorkbook или ActiveSheet, а на активный объект Range – как на Selection.

Если в коде VBA записана ссылка на рабочий лист, без указания к какой именно рабочей книге он относится, то Excel по умолчанию обращается к активной рабочей книге. Точно так же, если сослаться на диапазон, не указывая определённую рабочую книгу или лист, то Excel по умолчанию обратится к активному рабочему листу в активной рабочей книге.

Таким образом, чтобы сослаться на диапазон A1:B10 на активном рабочем листе активной книги, можно записать просто:

Смена активного объекта

Если в процессе выполнения программы требуется сделать активной другую рабочую книгу, другой рабочий лист, диапазон и так далее, то для этого нужно использовать методы Activate или Select вот таким образом:

Sub ActivateAndSelect()

   Workbooks("Книга2").Activate
   Worksheets("Лист2").Select
   Worksheets("Лист2").Range("A1:B10").Select
   Worksheets("Лист2").Range("A5").Activate

End Sub

Методы объектов, в том числе использованные только что методы Activate или Select, далее будут рассмотрены более подробно.

Свойства объектов

Каждый объект VBA имеет заданные для него свойства. Например, объект Workbook имеет свойства Name (имя), RevisionNumber (количество сохранений), Sheets (листы) и множество других. Чтобы получить доступ к свойствам объекта, нужно записать имя объекта, затем точку и далее имя свойства. Например, имя активной рабочей книги может быть доступно вот так: ActiveWorkbook.Name. Таким образом, чтобы присвоить переменной wbName имя активной рабочей книги, можно использовать вот такой код:

Dim wbName As String
wbName = ActiveWorkbook.Name

Ранее мы показали, как объект Workbook может быть использован для доступа к объекту Worksheet при помощи такой команды:

Workbooks("Книга1").Worksheets("Лист1")

Это возможно потому, что коллекция Worksheets является свойством объекта Workbook.

Некоторые свойства объекта доступны только для чтения, то есть их значения пользователь изменять не может. В то же время существуют свойства, которым можно присваивать различные значения. Например, чтобы изменить название активного листа на «Мой рабочий лист«, достаточно присвоить это имя свойству Name активного листа, вот так:

ActiveSheet.Name = "Мой рабочий лист"

Методы объектов

Объекты VBA имеют методы для выполнения определённых действий. Методы объекта – это процедуры, привязанные к объектам определённого типа. Например, объект Workbook имеет методы Activate, Close, Save и ещё множество других.

Для того, чтобы вызвать метод объекта, нужно записать имя объекта, точку и имя метода. Например, чтобы сохранить активную рабочую книгу, можно использовать вот такую строку кода:

Как и другие процедуры, методы могут иметь аргументы, которые передаются методу при его вызове. Например, метод Close объекта Workbook имеет три необязательных аргумента, которые определяют, должна ли быть сохранена рабочая книга перед закрытием и тому подобное.

Чтобы передать методу аргументы, необходимо записать после вызова метода значения этих аргументов через запятую. Например, если нужно сохранить активную рабочую книгу как файл .csv с именем «Книга2», то нужно вызвать метод SaveAs объекта Workbook и передать аргументу Filename значение Книга2, а аргументу FileFormat – значение xlCSV:

ActiveWorkbook.SaveAs "Книга2", xlCSV

Чтобы сделать код более читаемым, при вызове метода можно использовать именованные аргументы. В этом случае сначала записывают имя аргумента, затем оператор присваивания «:=» и после него указывают значение. Таким образом, приведённый выше пример вызова метода SaveAs объекта Workbook можно записать по-другому:

ActiveWorkbook.SaveAs Filename:="Книга2", [FileFormat]:=xlCSV

В окне Object Browser редактора Visual Basic показан список всех доступных объектов, их свойств и методов. Чтобы открыть этот список, запустите редактор Visual Basic и нажмите F2.

Рассмотрим несколько примеров

Пример 1

Этот отрывок кода VBA может служить иллюстрацией использования цикла For Each. В данном случае мы обратимся к нему, чтобы продемонстрировать ссылки на объект Worksheets (который по умолчанию берётся из активной рабочей книги) и ссылки на каждый объект Worksheet отдельно. Обратите внимание, что для вывода на экран имени каждого рабочего листа использовано свойство Name объекта Worksheet.

'Пролистываем поочерёдно все рабочие листы активной рабочей книги
'и выводим окно сообщения с именем каждого рабочего листа

Dim wSheet As Worksheet

For Each wSheet in Worksheets
   MsgBox "Найден рабочий лист: " & wSheet.Name
Next wSheet

Пример 2

В этом примере кода VBA показано, как можно получать доступ к рабочим листам и диапазонам ячеек из других рабочих книг. Кроме этого, Вы убедитесь, что если не указана ссылка на какой-то определённый объект, то по умолчанию используются активные объекты Excel. Данный пример демонстрирует использование ключевого слова Set для присваивания объекта переменной.

В коде, приведённом ниже, для объекта Range вызывается метод PasteSpecial. Этот метод передаёт аргументу Paste значение xlPasteValues.

'Копируем диапазон ячеек из листа "Лист1" другой рабочей книги (с именем Data.xlsx)
'и вставляем только значения на лист "Результаты" текущей рабочей книги (с именем CurrWb.xlsm)

Dim dataWb As Workbook

Set dataWb = Workbooks.Open("C:Data")

'Обратите внимание, что DataWb – это активная рабочая книга.
'Следовательно, следующее действие выполняется с объектом Sheets в DataWb.

Sheets("Лист1").Range("A1:B10").Copy

'Вставляем значения, скопированные из диапазона ячеек, на рабочий лист "Результаты"
'текущей рабочей книги. Обратите внимание, что рабочая книга CurrWb.xlsm не является
'активной, поэтому должна быть указана в ссылке.

Workbooks("CurrWb").Sheets("Результаты").Range("A1").PasteSpecial Paste:=xlPasteValues

Пример 3

Следующий отрывок кода VBA показывает пример объекта (коллекции) Columns и демонстрирует, как доступ к нему осуществляется из объекта Worksheet. Кроме этого, Вы увидите, что, ссылаясь на ячейку или диапазон ячеек на активном рабочем листе, можно не указывать этот лист в ссылке. Вновь встречаем ключевое слово Set, при помощи которого объект Range присваивается переменной Col.

Данный код VBA показывает также пример доступа к свойству Value объекта Range и изменение его значения.

'С помощью цикла просматриваем значения в столбце A на листе "Лист2",
'выполняем с каждым из них арифметические операции и записываем результат
'в столбец A активного рабочего листа (Лист1)

Dim i As Integer
Dim Col As Range
Dim dVal As Double

'Присваиваем переменной Col столбец A рабочего листа "Лист2"

Set Col = Sheets("Лист2").Columns("A")
i = 1

'Просматриваем последовательно все ячейки столбца Col до тех пор
'пока не встретится пустая ячейка

Do Until IsEmpty(Col.Cells(i))

   'Выполняем арифметические операции со значением текущей ячейки

   dVal = Col.Cells(i).Value * 3 - 1

   'Следующая команда записывает результат в столбец A
   'активного листа. Нет необходимости указывать в ссылке имя листа,
   'так как это активный лист рабочей книги.

   Cells(i, 1).Value = dVal
   i = i + 1

Loop

Оцените качество статьи. Нам важно ваше мнение:

Содержание рубрики VBA Excel на сайте «Время не ждёт». Систематизация статей по тематическим группам для ускорения поиска нужной информации по заданной теме.

Знакомство с VBA Excel

Начинаем программировать с нуля
Памятка для начинающих
Первая кнопка (для начинающих)
Первая форма (для начинающих)
Первая функция (для начинающих)
Правильные имена переменных и процедур
Свойства ячейки (объекта Range)
Свойство ActiveCell объекта Application
Свойство Selection объекта Application

Методы VBA Excel

Метод Application.Goto
Метод Application.InputBox (синтаксис, параметры)
Метод Application.Intersect (пересечение диапазонов)
Метод Application.OnKey
Метод Application.OnTime
Метод Application.Union (объединение диапазонов)
Метод Controls.Add пользовательской формы
Метод CreateTextFile (синтаксис, параметры)
Метод Find объекта Range
Метод FindNext объекта Range
Метод Hyperlinks.Add (создание гиперссылки)
Метод OpenTextFile (синтаксис, параметры)
Метод Range.AutoFill (автозаполнение ячеек)
Метод Range.Insert (вставка со сдвигом ячеек)
Метод Range.Justify (переупорядочивание текста)
Метод Range.PasteSpecial (специальная вставка)
Метод Range.Replace (замена текста в ячейках)
Метод Range.Show
Метод WorksheetFunction.Match (поиск позиции)
Метод WorksheetFunction.Sum – сумма аргументов
Метод WorksheetFunction.SumIf
Метод WorksheetFunction.SumIfs
Метод WorksheetFunction.Transpose
Метод WorksheetFunction.VLookup
Методы Count, CountA и CountBlank
Методы CountIf и CountIfs
Методы очистки ячеек (Range.Clear и другие)
Открытие сайта методом FollowHyperlink
Удаление ячеек со сдвигом (Range.Delete)

Объект Range в VBA Excel

Автоподбор высоты объединенной ячейки
Автоподбор ширины объединенной ячейки
Вставка пустой строки или столбца
Вставка формулы в ячейку
Выделенный диапазон ячеек (адрес, выбор, строки)
Выравнивание текста в ячейке
Вырезание, копирование и вставка ячеек (диапазонов)
Диапазон ячеек и массив (обмен значениями)
Диапазон ячеек пуст (определение)
Объединение ячеек и его отмена
Переменная диапазона ячеек (As Range)
Программное создание границ ячеек
Размер ячейки (высота строки, ширина столбца)
Свойства Column и Columns объекта Range
Свойства Row и Rows объекта Range
Свойство Areas объекта Range
Свойство Cells объекта Range
Свойство End объекта Range
Свойство Range.Characters
Свойство Range.CurrentRegion
Свойство Range.Hidden
Свойство Range.Offset
Свойство Range.Resize (синтаксис, примеры)
Свойство Range.Text
Свойство Range.WrapText (перенос текста)
Цвет текста (шрифта) в ячейке
Цвет ячейки (заливка, фон)
Узор (рисунок) в ячейке
Форматирование текста в ячейке (объект Font)
Ячейки (обращение, запись, чтение, очистка)

Объекты VBA Excel

Объект Collection (создание, методы, примеры)
Объект Dictionary (свойства, методы, примеры)
Объект DocumentProperties — свойства документа
Объект FileSystemObject
Объект PageSetup (параметры страницы)
Объект TextStream (свойства и методы)
Рабочая книга (открыть, создать новую, закрыть)
Рабочий лист (обращение, переименование, скрытие)
Рабочий лист (создание, копирование, удаление)
Регулярные выражения (объекты, свойства, методы)

Операторы в VBA Excel

Арифметические операторы
Логические операторы
Оператор Beep (одиночный звуковой сигнал)
Оператор If…Then…Else и функция IIf
Оператор On Error (обработка ошибок)
Оператор Open (синтаксис, параметры)
Оператор Select Case (синтаксис, примеры)
Оператор SendKeys (имитация нажатия клавиш)
Оператор With
Операторы сравнения
Операторы чтения и записи в файл

Переменные в VBA Excel

Глобальная переменная
Ключевое слово Me
Количество измерений массива
Массивы (одномерные, многомерные, динамические)
Пользовательские типы данных (оператор Type)
Тип данных Decimal
Типы данных

Примеры кода VBA Excel

Автоматическая запись текущей даты и времени
Автоматическое заполнение интервала дат (периода)
Бегущая, ползущая и танцующая строки
Буфер обмена (копирование, вставка, очистка)
Вставка рисунка в ячейку
Выбор случайной ячейки из диапазона
Генератор случайных чисел (Rnd и Randomize)
Генерация документов (реестр, массив, бланк)
Генерация документов и отчетов
Добавление кнопки в контекстное меню
Запуск макроса при изменении ячейки
Изменение свойств пользовательской формы
Имитация движения и кликов мыши
Квадратные ячейки (тетрадные клетки)
Копирование данных с одного листа на другой
Копирование и перемещение файлов
Копирование строк по условию
Номер последней заполненной строки
Определение координат элемента массива
Отбор неповторяющихся значений
Отбор уникальных значений с помощью Collection
Отбор уникальных значений с помощью Dictionary
Открыта или закрыта книга (проверка состояния)
Открытие файла другой программы из кода VBA Excel
Ошибки в таблице – поиск и исправление
Парсинг сайтов, html-страниц и файлов
Перебор листов в книге
Перемещение листа и его отмена
Переход к ячейке по адресу из формулы
Переход по ссылке к ячейке в другой книге
Поиск значения в таблице
Поиск и выделение дубликатов в столбце
Пользовательская автоформа (создание)
Проверка существования листа
Программное создание графика (диаграммы)
Программное создание модуля
Программное создание формы
Работа с умной таблицей
Расчет рабочего времени
Сбор данных из открытых книг
Секундомер в ячейке рабочего листа
Смещение умной таблицы вниз
Создание простого тестового задания
Создание таблицы (умной, обычной)
Создание файлов
Создание, копирование, перемещение папок
Сортировка массива
Сортировка таблицы (диапазона)
Сохранение книг и листов в PDF
Сохранение массива в текстовый файл
Список папок
Список файлов в папке
Сравнение прайс-листов
Сумма прописью (код пользовательской функции)
Удаление книги из собственного кода
Удаление повторяющихся значений в диапазоне ячеек
Удаление пустых строк
Удаление файлов
Учет расхода воды и других ресурсов
Число Пи (значение)
Экспорт и импорт пользовательской формы

Прочее в VBA Excel

Включение режима конструктора
Время работы макроса
Знаки подстановки для шаблонов
Кавычки в коде — двойные и ёлочки
Колонтитулы
Конвертация цвета из Long в RGB
Копирование, перемещение и поворот фигур
Объявление функций в 64-разрядных версиях
Округление чисел (особенности)
Открыть папку (каталог) в проводнике
Параметры и аргументы
Преобразование текста в число
Работа с трехмерными диапазонами
Работа с фигурами (Shapes)
Свойства файла — вывод информации о файле
Свойство Application.WindowState
Смена кодировки UTF-8 на ANSI (Windows-1251)
Смена раскладки клавиатуры
Сохранение файла рабочей книги
Сочетание клавиш для процедуры (макроса)
Стандартная палитра из 56 цветов
Стандартный диалог выбора файлов Application.GetOpenFilename

Работа с Word из кода VBA Excel

Bookmarks – закладки в документе Word
Вставка таблицы Excel в документ Word
Редактирование документов Word
Создание и открытие документов Word
Создание таблиц в документе Word
Управление приложением Word

Редактор VBA Excel

Debug — отладка программы
Вызов процедуры Sub из другой подпрограммы VBA
Защита паролем и снятие защиты проекта VBA
Личная книга макросов (создание, предназначение)
Макросы (запись, запуск, пример)
Модуль (импорт, экспорт, удаление)
Модуль, процедура, форма
Окно Immediate (отладка кода, вычисления)
Перенос кода процедуры и текста на новую строку

События VBA Excel

Событие Worksheet.SelectionChange

Функции в VBA Excel

Изменение значений других ячеек из функции
Пользовательская функция (синтаксис, компоненты)
Проверка переменных и выражений
Работа с текстом (функции)
Удаление лишних пробелов (LTrim, RTrim, Trim)
Функции Left, Mid, Right (вырезать часть строки)
Функции Space, String и StrReverse
Функция Beep API (звуковой сигнал, мелодия)
Функция Choose (синтаксис, компоненты, примеры)
Функция FileDateTime
Функция Filter (фильтрация массива)
Функция Format (синтаксис, параметры, примеры)
Функция FreeFile
Функция Hex
Функция InputBox (синтаксис, параметры, значения)
Функция InStr (синтаксис, параметры, примеры)
Функция InStrRev (синтаксис, параметры, примеры)
Функции Int и Fix
Функция Join (синтаксис, параметры, значения)
Функция MicroTimer
Функция MsgBox (синтаксис, параметры, значения)
Функция Replace (замена подстроки)
Функция Shell
Функция Split (синтаксис, параметры, значения)
Функция StrComp (сравнение строк)
Функция StrConv (смена регистра букв)
Функция Switch (синтаксис, примеры)
Функция Timer (примеры)
Функция Val (примеры)
Функция для вычисления факториала
Функции для работы с датой
Функция преобразования HTML-цвета в число
Функции преобразования типов данных

Циклы в VBA Excel

Цикл Do Until… Loop
Цикл Do While… Loop
Цикл For Each… Next
Цикл For… Next
Цикл While… Wend
Циклы (краткое описание)

Элементы управления в VBA Excel

ComboBox – заполнение поля со списком
ListBox – заполнение списка данными
Заполнение списка ComboBox по условию
Маска ввода в TextBox
Привязка события к элементу управления
Программное раскрытие ComboBox
Размеры и расположение элементов управления
Свойства SelStart, SelLength, SelText (TextBox)
Свойство Picture элементов управления
Сочетания клавиш для кнопок
Удаление элементов ActiveX с рабочего листа
Удаление элементов управления формы с листа
Элемент управления CheckBox (флажок)
Элемент управления ComboBox (поле со списком)
Элемент управления CommandButton (кнопка)
Элемент управления DTPicker
Элемент управления Frame (рамка)
Элемент управления Image
Элемент управления Label (метка, надпись)
Элемент управления ListBox (список)
Элемент управления MultiPage
Элемент управления OptionButton (переключатель)
Элемент управления RefEdit (редактор ссылок)
Элемент управления ScrollBar (полоса прокрутки)
Элемент управления SpinButton (счетчик)
Элемент управления TabStrip
Элемент управления TextBox (текстовое поле)
Элемент управления ToggleButton (выключатель)
Элемент управления TreeView (древовидная структура)

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!

automacro

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:

Assigning a Variable to a Object in VBA

It’s essential to understand how objects work to master VBA. You can learn more with our Interactive VBA Tutorial.

“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
    Set GetCollection = coll

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.)

vba objects video

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.

 
VBA Objects

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.

VBA Object Car

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

  1. Properties – These are used to set or retrieve a value.
  2. Methods – These are function or subs that perform some task on the objects data.
  3. 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

VBA Objects

 
What these icons mean is as follows

VBA Object Icons

 
 
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.

VBA Object nothing

 
If we try to run this line we get the following error

VBA Object Variable

 
There are three steps to creating a VBA object

  1. Declare the variable.
  2. Create a new object.
  3. 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

 
VBA Set

 
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

 
VBA Set Memory

 
When we assign values to these variables, VBA places the new values in the appropriate slots.

X = 25
Y = 12

 
VBA Basic Memory

 
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.

VBA Objects in Memory

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.

 
VBA Objects 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.

VBA 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.

VBA Object - Library

© 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:

  1. A new object is created in memory when we use the New keyword.
  2. The object variable contains only the memory address of the object.
  3. Using Set changes the address in the object variable.
  4. If an object is no longer referenced then VBA will automatically delete it.
  5. 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.)

VBA(VisualBasicForApplications)
– это объектно-ориентированный язык
макропрограммирования высокого уровня,
интегрированный во все программы пакетаMSOffice2003 и
предоставляющим возможности визуального
программирования. Основное отличие
программ на языке VBA от программ,
написанных на других языках программирования
(например, Basic, Pascal), состоит в том, что
наряду с обычными переменными и
константами, эти программы манипулируют
готовыми объектами приложений Microsoft
Office, такими, например, как документы,
абзацы, строки и слова Word; или рабочие
книги, рабочие листы и диапазоны ячеек
Excel.

VBA непосредственно связан с языком
Visual Basic (VB). Основное различие между ними
формулируется следующим образом: проекты
VBA выполняются только с помощью приложения,
поддерживающего VBA, в то время как Visual
Basic позволяет создавать полностью
автономные приложения. С другой стороны,
синтаксис языков VBA и VB практически
одинаков. Оба языка имеют почти одинаковые
интегрированные среды разработки.

Visual Basic для приложений является
объектно-ориентированным языком,
предоставляющим возможности визуального
программирования.

VBA содержит иерархию объектов, каждому
из которых соответствует свой набор
методов и свойств. Объекты представляют
собой фундаментальные «строительные»
блоки – почти все, что делается в среде
VBA, включает модификацию объектов

ОбъектомVBA считается некоторый
элемент, который можно отобразить в
окне приложения и на который можно
воздействовать некоторым образом,
изменяя его состояние. Например,Рабочая
книга
,Рабочийлист,Активнаяячейка,Диапазонявляются
объектами. К числу наиболее значимых
объектовExcelследует
отнести следующие.

Таблица 1. Объекты Excel

Объект

Краткая
характеристика

Application

(объект «Приложение»)

Этот
объект представляет собой само
приложение Excel в целом. Он включает в
себя глобальные устанавливаемые
параметры, такие, например, как
используемый стиль ссылок на ячейки
или режим проведения вычислений.
Кроме того, он включает в себя встроенные
функции Excel.

Windows

(семейство «Окна»)

Объекты
этого семейства используются при
управлении окном (сворачивании,
разворачивании, разбиении его на
части и т.д.) Принадлежащий к этому
семейству объект ActiveWindow представляет
собой активное в настоящий момент
окно.

Workbooks

(семейство
«Рабочие книги»)

Объекты
этого семейства определяют состояние
рабочей книги, например: не является
ли она доступной только для чтения;
или какой из листов рабочей книги
активен в настоящий момент. Принадлежащий
к этому семейству объект ActiveWorkbook —
это объект, который представляет
собой активную в настоящий момент
рабочую книгу.

Worksheets

(семейство
«Рабочие листы»)

Объекты
этого семейства используются при
копировании или удалении 45абочих
листов, их скрытии или отображении,
проведении вычислений для формул
рабочего листа. Принадлежащий к этому
семейству объект ActiveWorksheet — это
объект, который представляет собой
активный в настоящий момент рабочий
лист.

Range

(объект «Диапазон»)

Этот
объект позволяет изменять свойства
диапазона ячеек, например, используемый
шрифт, проверять или изменять содержимое
ячеек, вырезать или копировать
указанный диапазон, и многое другое.
Это наиболее часто используемый в
Excel объект. Принадлежащий к этому же
классу объектов объект ActiveCell
представляет собой активную в настоящий
момент ячейку. Следует обратить
внимание на то, что не существует
такого объекта, как Cell (ячейка)—
отдельно взятая ячейка представляет
собой частный случай объекта Range
(Диапозон).

Существуют сотни самых разнообразных
объектов VBA, многие из которых объединяются
в Семействаобъектов.Семейством
(Collection)
в VBA называется совокупность
однотипных объектов. Например, в Excel
семействоWorksheetsявляется совокупностью
всех рабочих листов — объектовWorksheet— в данной рабочей книге, а семействоLines— совокупностью прямых линий,
нарисованных на данном рабочем листе.
Составляющие семейство отдельные
объекты называютсяэлементамисемейства. Можно ссылаться на отдельные
элементы семейства, указывая в скобках
имя конкретного объекта.

Хотя семейства представляют собой
группы объектов, сами семейства также
являются одиночными объектами. Такой
собирательный объект-семействопредставляет собой всю совокупность
входящих в семейство объектов, и имеет
собственные свойства и методы, с помощью
которых можно изменять разом состояние
всех объектов семейства.

Например, оператор ActiveSheet.Lines.Delete
удаляет все нарисованные на активном
рабочем листе прямые линии.

Как правило, индивидуальные объекты,
являющиеся элементами семейств, имеют
гораздо больше свойств и методов, чем
соответствующий собирательный
объект-семейство. Например,
объект-семействоWorkbooksв Excel имеет
всего пять свойств (Application,Count,Creator,Item,Parent) и четыре метода
(Add,Close,Open,OpenText), в то
время как объектWorkbookимеет 59 свойств
и 42 метода.

Не все объекты приложений могут
группироваться в семейства — для
некоторых индивидуальных объектов не
существует соответствующих семейств.

Приведем краткий список наиболее часто
используемых семейств объектов Excel.

Таблица 2. Семейства объектов Excel

Семейство

Описание

Workbooks

Все
открытые в настоящий момент рабочие
книги. С помощью метода Open можно
открыть еще одну рабочую книгу. Метод
Add создает новую рабочую книгу.

Sheets

Включает
в себя все листы рабочей книги — как
обычные рабочие листы, так и листы
диаграмм. Наиболее часто используемые
методы — Add, Copy, Delete, Select.

Worksheets

Все
рабочие листы рабочей книги. Используются
те же методы, что и для семейства
Sheets.

Важнейшим понятием объектно-ориентированного
программирования является класс,
который определяется как проект, на
основе которого впоследствии будет
создан конкретный объект, т.е. класс
определяет имя объекта, его свойства и
действия, выполняемые над объектом. В
свою очередь объект является экземпляром
класса.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

Понравилась статья? Поделить с друзьями:
  • Объекты vba excel cell
  • Объектом обработки excel является файл с расширением ответ
  • Объекты userform vba excel
  • Объектом обработки excel является файл с расширением doc exe xls bmp
  • Объекты smartart в ms word позволяют создавать