All about excel миф

Содержание

  1. VBA Excel
  2. VBA Excel. Колонтитулы
  3. VBA Excel. Работа с трехмерными диапазонами
  4. VBA Excel. Список папок
  5. VBA Excel. Копирование строк по условию
  6. VBA Excel. Имитация движения и кликов мыши
  7. VBA Excel. Сбор данных из открытых книг
  8. VBA Excel. Определение координат элемента массива
  9. VBA Excel. Модуль, процедура, форма
  10. VBA Excel. Расчет рабочего времени
  11. VBA Excel. Проверка переменных и выражений
  12. VBA Excel. Преобразование текста в число
  13. VBA Excel. Запуск макроса при изменении ячейки
  14. VBA Excel. Работа с умной таблицей
  15. VBA Excel. Ключевое слово Me
  16. VBA Excel. Памятка для начинающих
  17. VBA Excel. Кавычки в коде — двойные и ёлочки
  18. VBA Excel. Debug — отладка программы
  19. VBA Excel. Копирование, перемещение и поворот фигур
  20. Начало работы с VBA в Office
  21. Причины использования VBA
  22. Автоматизация и повторяемость
  23. Расширения возможностей взаимодействия с пользователем
  24. Взаимодействие приложений Office
  25. Другой способ
  26. Введение в программирование на VBA
  27. Использование кода для выполнения операций приложениями
  28. Объектная модель
  29. Методы
  30. Свойства
  31. Макросы и редактор Visual Basic
  32. Включение вкладки «Разработчик»
  33. Проблемы безопасности
  34. Запись макроса
  35. Запись макроса
  36. Использование справки разработчика
  37. Редактирование кода
  38. Советы и приемы программирования
  39. Начните с примеров
  40. Упрощение задачи
  41. Ошибки и отладка
  42. Правильное использование справочных материалов
  43. Поиск в форумах и группах
  44. Более подробное изучение программирования
  45. Переменные
  46. Ветвление и циклы
  47. Все приложения на вкладке «Мой Office»: примеры кода
  48. Создание электронной почты в Outlook
  49. Удаление пустых строк на листе Excel
  50. Удаление пустых текстовых полей в PowerPoint
  51. Копирование контакта из Outlook в Word
  52. Поддержка и обратная связь

VBA Excel

VBA Excel – это отличный инструмент для автоматизации многих офисных и других учетных и вычислительных процессов. В этой рубрике представлены небольшие заметки по VBA Excel со справочной информацией, которые можно использовать как памятки при написании кода. VBA часто применяется для автоматизации офисных и других работ, которые ведутся в книгах Excel. Это и учет сотрудников, и начисление зарплат и налогов, и формирование различных бланков, и обработка больших объемов каких-либо данных. То, чем приходилось мне пользоваться на практике, также описано в этой рубрике и в рубрике «Офисная работа».

Смотрите Содержание рубрики VBA Excel по тематическим разделам со ссылками на все статьи.

VBA Excel. Колонтитулы

Создание верхнего и нижнего колонтитулов из кода VBA Excel: присвоение текста и его выравнивание, назначение шрифта, его размера, цвета и начертания. Подробнее » VBA Excel. Колонтитулы

VBA Excel. Работа с трехмерными диапазонами

Работа с трехмерными диапазонами Excel из кода VBA. Выделение трехмерного диапазона, задание границ, заливка, присвоение значений. Подробнее » VBA Excel. Работа с трехмерными диапазонами

VBA Excel. Список папок

Получение списка папок 1, 2 и 3 уровней вложенности с помощью кода VBA Excel. SubFolders — коллекция подпапок, расположенных в указанной папке. Подробнее » VBA Excel. Список папок

VBA Excel. Копирование строк по условию

Копирование строк по условию из существующего набора данных в отдельную таблицу с помощью кода VBA Excel. Определение числа строк в исходной таблице. Подробнее » VBA Excel. Копирование строк по условию

VBA Excel. Имитация движения и кликов мыши

Имитация движения и кликов левой и правой кнопками мыши из кода VBA Excel. Эмуляция перемещения курсора и определение его текущих координат. Подробнее » VBA Excel. Имитация движения и кликов мыши

VBA Excel. Сбор данных из открытых книг

Сбор данных из открытых книг Excel с помощью кода VBA, при условии, что данные находятся на листах с одним именем и в одноименных ячейках. Подробнее » VBA Excel. Сбор данных из открытых книг

VBA Excel. Определение координат элемента массива

Определение координат выбранного элемента двумерного массива из кода VBA Excel при обходе его элементов циклом For Each… Next. Адрес исходной ячейки. Подробнее » VBA Excel. Определение координат элемента массива

VBA Excel. Модуль, процедура, форма

Знакомство с понятиями модуль, процедура, форма в VBA Excel. Модули разных типов. Создание пользовательской формы. Встроенные диалоговые окна. Подробнее » VBA Excel. Модуль, процедура, форма

VBA Excel. Расчет рабочего времени

Расчет рабочего времени за период, ограниченный двумя датами, в течение одного года с помощью кода VBA Excel. Функция для расчета рабочего времени. Подробнее » VBA Excel. Расчет рабочего времени

VBA Excel. Проверка переменных и выражений

Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject. Подробнее » VBA Excel. Проверка переменных и выражений

VBA Excel. Преобразование текста в число

Преобразование текста в число с помощью кода VBA Excel. Массовое преобразование чисел из текстового формата в числовой в заданном диапазоне. Подробнее » VBA Excel. Преобразование текста в число

VBA Excel. Запуск макроса при изменении ячейки

Запуск макроса (процедуры) из кода VBA Excel при изменении значения ячейки вручную или программным способом, а также при нажатии клавиши Delete. Подробнее » VBA Excel. Запуск макроса при изменении ячейки

VBA Excel. Работа с умной таблицей

Работа с умной таблицей из кода VBA Excel. Обращение к ячейкам, строкам и столбцам умной таблицы. Добавление и удаление строк и столбцов. Подробнее » VBA Excel. Работа с умной таблицей

VBA Excel. Ключевое слово Me

Ключевое слово Me используется в VBA Excel при написании процедур, находящихся в модулях объектов, и представляет собой эти объекты. Примеры с Me. Подробнее » VBA Excel. Ключевое слово Me

VBA Excel. Памятка для начинающих

Памятка для начинающих по коду VBA Excel. Краткий справочник по часто используемым выражениям при написании программного кода. Подробнее » VBA Excel. Памятка для начинающих

VBA Excel. Кавычки в коде — двойные и ёлочки

Двойные кавычки и кавычки «ёлочки» в коде VBA Excel. Коды символов кавычек и ввод кавычек «ёлочек» в редакторе VBA Excel с клавиатуры. Примеры. Подробнее » VBA Excel. Кавычки в коде — двойные и ёлочки

VBA Excel. Debug — отладка программы

Отладка кода программы (процедуры) в редакторе VBA Excel. Горячие клавиши для команд меню Debug, окна Immediate и Locals, пункт Compile VBAProject. Подробнее » VBA Excel. Debug — отладка программы

VBA Excel. Копирование, перемещение и поворот фигур

Копирование, перемещение и поворот фигур с помощью кода VBA Excel, привязка скопированной фигуры к координатам заданной ячейки. Подробнее » VBA Excel. Копирование, перемещение и поворот фигур

Источник

Начало работы с VBA в Office

Постоянно возникает проблема, вызванная повторяющейся очисткой данных в 50 таблицах в Word? Хотите, чтобы при открытии определенного документа пользователи получали запрос на добавление данных? Не знаете, как быстро и легко перенести список контактов из Microsoft Outlook в таблицу Microsoft Excel?

Вы можете выполнять эти задачи и значительно больше, используя Visual Basic для приложений (VBA) для Office — простой, но мощный язык программирования, который можно использовать для расширения приложений Office.

Данная статья предназначена для опытных пользователей Office, которые желают познакомиться с VBA и получить некоторое представление о том, как программирование может помочь им настроить Office.

Набор приложений Office обладает множеством возможностей. Существует множество разных способов создания, форматирования и управления документами, электронной почтой, базами данных, формами, электронными таблицами и презентациями. Значительное преимущество программирования на VBA в Office заключается в том, что почти каждое действие, осуществляемое с мышью, клавиатурой или диалоговым окном, можно выполнить с помощью VBA. Если действие можно выполнить с помощью VBA, значит в дальнейшем его можно легко осуществлять сотни раз. (На самом деле автоматизация повторяющихся задач — одно из наиболее частых применений VBA в Office).

Помимо возможности написания скрипта VBA для ускорения повседневных задач, VBA можно использовать для добавления новых функций в приложения Office или создания запросов и взаимодействия с пользователем ваших документов в соответствии с потребностями вашей организации. Например, можно написать код VBA, выводящий всплывающее сообщение, которое напоминает пользователям о необходимости сохранения документа на определенном сетевом диске при первой попытке его сохранения.

В этой статье описываются некоторые основные причины для использования возможностей программирования на VBA. Здесь описывается язык VBA и встроенные средства, которые можно использовать для работы со своими решениями. И, наконец, в данной статье можно найти советы и приемы, чтобы избежать некоторых распространенных ошибок программирования.

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Причины использования VBA

Есть несколько основных причин использовать программирование на VBA в Office.

Автоматизация и повторяемость

Программирование на VBA эффектно и эффективно при создании решений для устранения повторяющихся проблем форматирования и исправлений. Например, вам когда-нибудь приходилось изменять стиль абзаца в верхней части каждой страницы в Word? Или менять формат нескольких таблиц, скопированных из Excel в документ Word или электронную почту Outlook? А вносить одинаковые изменения в несколько контактов Outlook?

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

Расширения возможностей взаимодействия с пользователем

Иногда некоторые действия пользователей с документом или приложением Office обязательны или желательны, но не доступны в стандартном приложении. Например, нужно уведомлять пользователей о необходимости что-то сделать при открытии, сохранении или печати документа.

Взаимодействие приложений Office

Нужно скопировать все контакты из Outlook в Word и отформатировать их определенным способом? Или же нужно переместить данные из Excel в набор слайдов PowerPoint? Иногда простое копирование и вставка не работают так, как надо, или же это происходит слишком медленно. Воспользуйтесь программированием на VBA для работы с данными в двух или более приложениях Office одновременно, а затем измените содержимое в одном приложении с учетом содержимого в другом.

Другой способ

Программирование на VBA — это мощное решение, но данный подход не всегда является оптимальным. Иногда, чтобы достичь поставленных целей, имеет смысл воспользоваться другими методами.

Важнейший вопрос состоит в поиске более легкого способа. Перед запуском проекта VBA обратите внимание на встроенные инструменты и стандартные функциональные возможности. Например, если необходимо выполнить времяемкую задачу редактирования или размещения элементов, для решения проблемы следует рассмотреть возможность использования стилей или сочетания клавиш. Можете ли вы выполнить задачу единожды, а затем повторить ее с помощью сочетания клавиш CTRL+Y («Повторить»)? Можно ли создать документ правильного формата или с нужным шаблоном и затем скопировать содержимое в новый документ?

Приложения Office обладают множеством возможностей. Возможно, нужное решение уже в них предусмотрено. Узнайте больше об Office, прежде чем начинать программирование.

Перед созданием проекта VBA убедитесь, что у вас есть время на работу с VBA. Программирование требует внимания и может оказаться непредсказуемым. Если вы начинающий программист, тем более не стоит увлекаться программированием, если не хватает времени на внимательную работу. Попытки написать «скрипт на скорую руку» для решения проблемы в сжатые сроки может привести к напряженной ситуации. Если вы торопитесь, воспользуйтесь более привычными методами, даже если они сопряжены с монотонностью и повторениями.

Введение в программирование на VBA

Использование кода для выполнения операций приложениями

Написание кода может казаться очень сложным и непонятным процессом. На самом деле, его базовые принципы основаны на применении повседневной логики и вполне доступны. Объекты в приложениях Microsoft Office, созданные для получения инструкций, можно сравнить с кнопками телефона. Когда вы нажимаете кнопку, телефон распознает команду и включает соответствующую цифру в набираемую последовательность. При программировании вы взаимодействуете с приложением, отправляя инструкции различным объектам. Эти объекты эффективны, но у них есть свои ограничения. Они смогут делать только то, для чего были разработаны, и выполнять только ваши инструкции.

Например, представьте себе пользователя, который открывает документ Word, вносит несколько изменений, а затем сохраняет и закрывает его. Для программирования на VBA приложение Word предоставляет объект Document. Используя код VBA, можно заставить объект Document выполнять такие действия, как открытие, сохранение и закрытие.

В следующем разделе описывается организация объектов.

Объектная модель

Разработчики организуют объекты программирования в виде иерархии, и такая иерархия называется объектной моделью приложения. В Word, например, есть объект верхнего уровня Application, который содержит объект Document. Объект Document содержит объекты Paragraph и т. д. В объектных моделях приблизительно отражено то, что вы видите в пользовательском интерфейсе. Они являются концептуальной картой приложения и его возможностей.

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

Уже существующим объектом можно управлять, задавая его свойства и вызывая его методы. Если представить объект в виде имени существительного, свойства станут прилагательными, описывающими существительное, а методы — глаголами, которые приводят его в действие. Изменение свойства приводит к модификации определенной характеристики внешнего вида или поведения объекта. Вызов одного из методов объекта заставляет последний выполнить какое-либо действие.

Код VBA в этой статье взаимодействует с приложением Office, в котором многие объекты, которыми управляет код, уже настроены и работают (например, объект Application приложения, Worksheet в Excel, Document в Word, Presentation в PowerPoint, объекты Explorer и Folder в Outlook). Узнав основную структуру объектной модели и некоторые ключевые свойства объекта Application, которые предоставляют доступ к его текущему состоянию, можно расширить возможности приложения Office с помощью VBA в Office.

Методы

В Word, например, можно изменить свойства и вызвать методы текущего документа Word с помощью свойства ActiveDocument объекта Application. Это свойство ActiveDocument возвращает ссылку на объект Document, активный в приложении Word. «Возвращает ссылку на» означает «предоставляет доступ к».

В приведенном ниже коде выполняется именно то, что сказано; т. е. активный документ приложения сохраняется.

Прочитайте код слева направо: «В этом приложении с документом, на который ссылается ActiveDocument, вызовите метод Save «. Имейте в виду, что Save — это простейшая форма метода; для этого не требуется никаких подробных инструкций от вас. Объекту Document дается команда сохранения (Save), а дополнительные данные вводить не нужно.

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

Значения, которые указываются в скобках после имени метода — это параметры. Здесь новое имя файла — параметр метода SaveAs.

Свойства

Для задания свойства используйте такой же синтаксис, что и для чтения свойства. В приведенном ниже коде выполняется метод для выбора ячейки A1 в Excel и затем задается свойство для записи данных в ячейку.

Первая задача при программировании на VBA — осознать объектную модель каждого приложения Office и научиться читать синтаксис объекта, метода и свойства. Во всех приложениях Office объектные модели похожи, но каждая из них обладает особенными характеристиками в соответствии с типом документов и объектов, которыми управляет.

В первой строке фрагмента кода указан объект Application, на этот раз это приложение Excel, а затем объект ActiveSheet, который предоставляет доступ к активному листу. После этого используется термин , который не так знаком, Range, что означает «определить диапазон ячеек таким образом». Код указывает Range создать себя только с A1 в качестве определенного набора ячеек. Другими словами, в первой строке кода объявляется объект Range и запускается метод для его выбора. Результат автоматически сохраняется в другом свойстве объекта Application с именем Selection.

Во второй строке кода задается значение свойства Value объекта Selection, равное «Hello World» и отображающееся в ячейке A1.

Самый простой код VBA может предоставлять доступ к объектам в приложении Office, с которым вы работаете, и задавать их свойства. Например, можно получить доступ к строкам в таблице Word и изменить их форматирование в скрипте VBA.

Это звучит просто, но может быть невероятно полезно. Написав такой код, можно освоить всю мощь программирования для внесения одинаковых изменений в несколько таблиц или документов в соответствии с определенной логикой или каким-то условием. Сделать 1000 изменений для компьютера почти то же самое, что 10, поэтому при работе с большими документами и при решении множества проблем VBA может оказаться очень полезен и сэкономить много времени.

Макросы и редактор Visual Basic

Теперь вы кое-что знаете об объектных моделях в приложениях Office. Возможно, вам не терпится попробовать вызвать методы объекта, задать его свойства и отреагировать на события объекта. Для этого необходимо написать свой код так, чтобы он распознавался в Office. Обычно это делается с помощью редактора Visual Basic. Несмотря на то, что он установлен по умолчанию, многие пользователи даже не догадываются о его наличии до тех пор, пока не включат его на ленте.

Все приложения Office используют ленту. Одной из вкладок на ленте является вкладка Разработчик, где можно вызвать редактор Visual Basic и другие инструменты разработчика. Так как в Office вкладка Разработчик не показана по умолчанию, необходимо вывести ее на экран, выполнив указанные ниже действия.

Включение вкладки «Разработчик»

На вкладке Файл выберите Параметры, чтобы открыть диалоговое окно Параметры.

Выберите пункт Настроить ленту в левой части диалогового окна.

В разделе Выбрать команды, расположенном слева в окне, выберите Часто используемые команды.

В разделе Настроить ленту, который находится справа в диалоговом окне, выберите Основные вкладки в раскрывающемся списке, а затем установите флажок Разработчик.

Нажмите кнопку OK.

В Office 2007 показ вкладки Разработчик выполняется путем нажатия кнопки Office, выбора пункта Параметры, а затем установки флажка Показать вкладку «Разработчик» на ленте в категории Популярные диалогового окна Параметры.

После включения вкладки Разработчик можно легко найти кнопки Visual Basic и Макрос.

Рис. 1. Кнопки на вкладке «Разработчик»

Проблемы безопасности

Для защиты документов Office от вирусов и вредоносных макросов не сохраняйте код макросов в стандартных документах Office со стандартным расширением файла. Следует сохранить код в файле с особым расширением. Например, сохраняйте макросы не в стандартном документе Word с расширением DOCX, а в специальном документе Word с поддержкой макросов и расширением DOCM.

При открытии DOCM-файла система безопасности Office все равно может запретить запуск макросов в документе, сообщая или не сообщая об этом. Изучите параметры и настройки центра управления безопасностью во всех приложениях Office. По умолчанию макросы отключены, но пользователь оповещается об этом и может включить их.

Можно указать специальные папки, в которых можно выполнять макросы, создав надежные расположения, надежные документы или надежных издателей. Самый универсальный способ — использовать надежных издателей. Этот способ подходит для работы с документами, у которых есть распространяемые вами цифровые подписи. Чтобы получить дополнительные сведения о параметрах безопасности в определенном приложении Office, откройте диалоговое окно Параметры, а затем выберите Центр управления безопасностью и Параметры центра управления безопасностью.

Некоторые приложения Office, такие как Outlook, сохраняют макросы по умолчанию в основном шаблоне на локальном компьютере. Хотя это позволяет уменьшить количество проблем с безопасностью на локальном компьютере при выполнении собственных макросов, для распространения своих макросов в этом случае потребуется стратегия развертывания.

Запись макроса

Если нажать кнопку Макрос на вкладке Разработчик, открывается диалоговое окно Макрос, которое предоставляет доступ к подпрограммам или макросам VBA, которые можно использовать из определенного документа или приложения. Кнопка Visual Basic открывает редактор Visual Basic, где можно создавать и редактировать код VBA.

На вкладке Разработчик в Word и Excel также есть кнопка Запись макроса, которая автоматически создает код VBA, позволяющий воспроизводить ваши действия в приложении. Запись макроса — это великолепное средство, которое можно использовать для изучения VBA. Читая такой код, можно понять язык VBA и объединить знания пользователя и программиста Office. Только помните о том, что этот код может быть запутанным, так как редактор макросов делает допущения насчет ваших намерений, которые не всегда точны.

Запись макроса

Создайте книгу в Excel и откройте вкладку Разработчик на ленте. Нажмите кнопку Запись макроса и оставьте все параметры по умолчанию в диалоговом окне Запись макроса, в том числе имя Макрос1 и расположение Эта книга.

Нажмите кнопку ОК, чтобы начать запись макроса. Обратите внимание, что текст кнопки изменяется на Остановить запись. Нажмите эту кнопку, когда выполните все записываемые действия.

Выберите ячейку B1 и введите классическую первую строку программиста — Hello World. Прекратите ввод текста и посмотрите на кнопку Остановить запись. Она серая, так как Excel ждет, пока вы завершите ввод значения ячейки.

Выберите ячейку B2, чтобы завершить действие в ячейке B1, а затем нажмите кнопку Остановить запись.

Выберите пункт Макросы на вкладке Разработчик, выберите макрос Макрос1, если он еще не выбран, и нажмите кнопку Изменить, чтобы просмотреть код Макрос1 в редакторе Visual Basic.

Рис. 2. Код макроса в редакторе Visual Basic

Созданный макрос должен выглядеть указанным ниже образом.

Учтите схожие моменты с предыдущим примером кода, в котором выбирается ячейка A1, и отличия от него. В этом примере кода выбирается ячейка B1, а затем строка «Hello World» записываются в активную ячейку. Кавычки вокруг текста обозначают строковое значение (в противоположность числовому значению).

Вспомните, что для отображения кнопки Остановить запись нужно было выбрать ячейку B2. Это действие также задается в строке кода. Средство записи макроса записывает каждое нажатие клавиши.

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

Когда средство записи макроса генерирует код, оно использует сложный алгоритм для определения нужных методов и свойств. Если не удается распознать данное свойство, пользователь может воспользоваться множеством ресурсов. Например, в записанном макросе средство записи макроса сгенерировало код, который ссылается на свойство FormulaR1C1. Не знаете, что это значит?

Помните, что объект Application используется во всех макросах VBA. Записанный код работает с приложением в начале каждой строки.

Использование справки разработчика

Выберите FormulaR1C1 в записанном макросе и нажмите F1. Система справки запустит быстрый поиск, определит, что нужные темы есть в разделе «Разработчик» справки Excel, и укажет свойство FormulaR1C1. Можно щелкнуть ссылку, чтобы прочитать описание свойства, но прежде обратите внимание на ссылку Справочник по объектной модели Excel в нижней части окна. Щелкните ее, чтобы просмотреть список объектов, которые Excel использует в объектной модели для описания листов и их компонентов.

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

Редактирование кода

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

Иногда самый лучший способ изучить программирование — вносить небольшие изменения в определенный рабочий код и смотреть, что получается. Попробуйте сделать это сейчас. Откройте Макрос1 в редакторе Visual Basic и измените код указанным ниже образом.

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

Для запуска сохранять код не требуется, поэтому вернитесь в документ Excel, выберите Макросы на вкладке Разработчик, выберите Макрос1 и нажмите кнопку Запустить. Теперь в ячейке A1 есть текст Wow!, а вокруг него размещена граница из двойных линий.

Рис. 3. Результаты первого макроса

Только что вы записали макрос, прочитали документацию по объектной модели и написали простую программу на VBA, которая что-то делает. Поздравляем!

Программа не работает? Читайте дальше и узнайте о методах отладки в VBA.

Советы и приемы программирования

Начните с примеров

Сообщество программистов на VBA очень большое; поиск в Интернете почти всегда может дать пример кода на VBA, который выполняет почти те же действия, которые необходимы вам. Если не удается найти хороший пример, попробуйте разбить задачу на более мелкие модули и выполнить поиск каждого из них. Или попробуйте найти более общую, но аналогичную задачу. Если начать с примеров, это может сэкономить много времени.

Это не означает, что в Интернете всегда доступен бесплатный и качественный код. В действительности, в найденных программах могут быть ошибки. Идея в том, что примеры из Интернета или документации по VBA помогают начать работу. Помните, что для изучения программирования требуется время и умственные усилия. Перед тем как использовать очередное решение для решения проблемы, спросите себя, подходит ли VBA для этого.

Упрощение задачи

Программирование может быстро стать сложной задачей. Важно, особенно для новичка, разбивать задачу на мельчайшие логические модули, а затем отдельно писать и проверять каждую часть. Если перед вами слишком много кода и вы запутались, остановитесь и отложите задачу. Когда вы к ней вернетесь, скопируйте небольшую часть задачи в новый модуль, разберитесь с ней, напишите работающий код и проверьте его. Затем займитесь следующей частью.

Ошибки и отладка

Существует два основных вида ошибок программирования: синтаксические ошибки, которые нарушают грамматические правила языка программирования и ошибки времени выполнения, которые синтаксически правильны, но вызывают сбой, когда VBA пытается выполнить код.

Хотя исправлять синтаксические ошибки неприятно, их легко обнаружить; редактор Visual Basic выдает сопровождающееся звуковым сигналом сообщение об ошибке и меняет цвет текста, если при вводе кода найдена синтаксическая ошибка.

Например, в VBA строковые значения должны быть заключены в двойные кавычки. Чтобы узнать, что происходит при использовании одиночных кавычек, вернитесь в редактор Visual Basic и замените строку «Wow!» в примере кода на «Wow!» (т. е. слово Wow в одинарных кавычках). Если выбрать следующую строку, среагирует редактор Visual Basic. Сообщение об ошибке «Ошибка компиляции. Ожидается: выражение» не особо помогает, но строка, содержащая ошибку, становится красной, что говорит о синтаксической ошибке в этой строке. В результате программа не будет запускаться.

Нажмите кнопку ОК и измените текст на «Wow!».

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

Например, откройте редактор Visual Basic и измените имя свойства Value на ValueX в макросе, намеренно вызывая ошибку среды выполнения, так как у объекта Range нет свойства ValueX. Вернитесь к документу Excel, откройте диалоговое окно Макрос и запустите Макрос1 еще раз. Вы увидите окно сообщения Visual Basic с описанием ошибки во время выполнения с текстом «Объект не поддерживает это свойство метода». Хотя этот текст не указан, выберите Отладка , чтобы узнать больше.

После возвращения в редактор Visual Basic будет включен специальный режим отладки, в котором желтым цветом выделяется строка кода с ошибкой. Как и ожидалось, желтым выделена строка со свойством ValueX.

Можно внести изменения в исполняемый код VBA, поэтому измените ValueX на Value и нажмите маленькую зеленую кнопку воспроизведения в меню Отладка. Программа должна запуститься без ошибок.

Будет полезно узнать, как эффективнее использовать отладчик для более длинных и сложных программ. Хотя бы изучите, как устанавливать точки останова, чтобы прекращать выполнение программы там, где нужно взглянуть на код, как добавлять контрольные значения, чтобы просматривать значения разных переменных и свойств во время выполнения кода, и как пошагово, строка за строкой, выполнять код. Все эти возможности доступны в меню Отладка, а серьезный пользователь отладчика обычно запоминает соответствующие сочетания клавиш.

Правильное использование справочных материалов

Чтобы открыть справочник разработчика, встроенный в справку Office, откройте справку в любом приложении Office, выбрав вопросительный знак на ленте или нажав клавишу F1. Затем справа от кнопки Поиск выберите стрелку раскрывающегося меню для фильтрации содержимого. Выберите Справочник разработчика. Если на левой панели не отображается содержание, щелкните маленький значок книги, чтобы открыть его, и разверните справочник по объектной модели.

Рис. 5. Фильтрация справки разработчика применяется ко всем приложениям Office

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

Конечно, центр разработки Microsoft Office — это прекрасный портал со статьями, советами и форумами сообщества.

Поиск в форумах и группах

Рано или поздно все программисты попадают в ситуацию, когда невозможно решить какую-либо проблему, даже прочитав все найденные статьи и проведя много бессонных ночей в поисках ее решения. К счастью, в Интернете появилось сообщество разработчиков, которые помогают друг другу при решении задач программирования.

Если поискать в Интернете «форум разработчиков Office», можно найти несколько таких групп обсуждений. Можно поискать «разработка Office» или описание проблемы и найти нужные форумы, блоги и статьи.

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

Далее описаны некоторые вопросы этикета, которых следует придерживаться при публикации на форуме разработчиков.

Перед публикацией поищите на сайте часто задаваемые вопросы или инструкции, которые следует соблюдать. Убедитесь, что публикация соответствует этим инструкциям и расположена в нужном разделе форума.

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

Опишите проблему четко и кратко и укажите действия, выполненные для решения проблемы. Не спешите и напишите вопрос, как можно лучше, даже если вы взволнованны или вам не хватает времени. Опишите ситуацию так, чтобы читатели поняли ее после первого прочтения.

Будьте вежливы и выражайте благодарность за все ответы.

Более подробное изучение программирования

Хотя это короткая статья, и в ней представлена лишь малая часть сведений о VBA и программировании, надеюсь, ее будет достаточно для начала.

В этом разделе кратко описываются некоторые другие важные темы.

Переменные

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

Чтобы использовать переменную в VBA, необходимо сообщить VBA, какой тип представляет переменная, с помощью оператора Dim. Затем задается значение переменной, и она используется для установки других переменных и свойств.

Ветвление и циклы

В примерах простых программ в этой статье код выполняется строка за строкой, сверху вниз. Реальные возможности программирования состоят в том, что можно определять, какие строки кода выполнять, в зависимости от одного или нескольких указанных условий. Эти возможности можно расширить, если повторять операцию нужное количество раз. Например, приведенный ниже пример кода расширяет Макрос1.

Введите или вставьте код в редакторе Visual Basic и запустите его. Следуйте инструкциям в появившемся окне сообщений и измените текст в ячейке A1 с «Wow!» на «Yes!», а затем выполните программу еще раз, чтобы ознакомиться с возможностями циклов. В этом примере кода показаны переменные, ветвление и циклы. Просмотрите его внимательно после выполнения и попробуйте определить, что происходит после выполнения каждой строки.

Все приложения на вкладке «Мой Office»: примеры кода

Вот несколько скриптов, которые можно попробовать. Каждый из них решает реальную задачу Office.

Создание электронной почты в Outlook

Помните, что бывают случаи, когда нужно автоматизировать электронную почту в Outlook или использовать шаблоны.

Удаление пустых строк на листе Excel

Помните, что можно выбрать столбец ячеек и запустить этот макрос, чтобы удалить все строки в выбранном столбце с пустыми ячейками.

Удаление пустых текстовых полей в PowerPoint

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

Копирование контакта из Outlook в Word

Обратите внимание, что этот код копирует открытый контакт из Outlook в открытый документ Word. Этот код работает, только если в Outlook открыт контакт.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Pizza in a pizza oven

Yum.

Why use VBA in Excel?

Because wood-fired pizza is the best!

But seriously.

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

VBA developer tab

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

VBA editor

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

Welcome to XYZ notebook message example

Ta da!

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Process the XYZ report message example

Click “yes” or hit Enter.

Thanks for processing the XYZ report message example

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

For-Next loop results

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Happy coding!

Learning Resources

  • Excel VBA Programming for Dummies, John Walkenbach
  • Get Started with VBA, Microsoft Documentation
  • Learning VBA in Excel, Lynda

A bit about me

I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Время на прочтение
7 мин

Количество просмотров 311K

Приветствую всех.

В этом посте я расскажу, что такое VBA и как с ним работать в Microsoft Excel 2007/2010 (для более старых версий изменяется лишь интерфейс — код, скорее всего, будет таким же) для автоматизации различной рутины.

VBA (Visual Basic for Applications) — это упрощенная версия Visual Basic, встроенная в множество продуктов линейки Microsoft Office. Она позволяет писать программы прямо в файле конкретного документа. Вам не требуется устанавливать различные IDE — всё, включая отладчик, уже есть в Excel.

Еще при помощи Visual Studio Tools for Office можно писать макросы на C# и также встраивать их. Спасибо, FireStorm.

Сразу скажу — писать на других языках (C++/Delphi/PHP) также возможно, но требуется научится читать, изменять и писать файлы офиса — встраивать в документы не получится. А интерфейсы Microsoft работают через COM. Чтобы вы поняли весь ужас, вот Hello World с использованием COM.

Поэтому, увы, будем учить Visual Basic.

Чуть-чуть подготовки и постановка задачи

Итак, поехали. Открываем Excel.

Для начала давайте добавим в Ribbon панель «Разработчик». В ней находятся кнопки, текстовые поля и пр. элементы для конструирования форм.

Появилась вкладка.

Теперь давайте подумаем, на каком примере мы будем изучать VBA. Недавно мне потребовалось красиво оформить прайс-лист, выглядевший, как таблица. Идём в гугл, набираем «прайс-лист» и качаем любой, который оформлен примерно так (не сочтите за рекламу, пожалуйста):

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

Результат, которого хотим добиться, выглядит примерно так:

Разумеется, если смотреть прайс только на компьютере, то можно добавить фильтры и будет гораздо удобнее искать нужный товар. Однако мы хотим научится кодить и задача вполне подходящая, не так ли?

Кодим

Для начала требуется создать кнопку, при нажатии на которую будет вызываться наша програма. Кнопки находятся в панели «Разработчик» и появляются по кнопке «Вставить». Вам нужен компонент формы «Кнопка». Нажали, поставили на любое место в листе. Далее, если не появилось окно назначения макроса, надо нажать правой кнопкой и выбрать пункт «Назначить макрос». Назовём его FormatPrice. Важно, чтобы перед именем макроса ничего не было — иначе он создастся в отдельном модуле, а не в пространстве имен книги. В этому случае вам будет недоступно быстрое обращение к выделенному листу. Нажимаем кнопку «Новый».

И вот мы в среде разработки VB. Также её можно вызвать из контекстного меню командой «Исходный текст»/«View code».

Перед вами окно с заглушкой процедуры. Можете его развернуть. Код должен выглядеть примерно так:

Sub FormatPrice()End Sub

Напишем Hello World:

Sub FormatPrice()
    MsgBox "Hello World!"
End Sub

И запустим либо щелкнув по кнопке (предварительно сняв с неё выделение), либо клавишей F5 прямо из редактора.

Тут, пожалуй, следует отвлечься на небольшой ликбез по поводу синтаксиса VB. Кто его знает — может смело пропустить этот раздел до конца. Основное отличие Visual Basic от Pascal/C/Java в том, что команды разделяются не ;, а переносом строки или двоеточием (:), если очень хочется написать несколько команд в одну строку. Чтобы понять основные правила синтаксиса, приведу абстрактный код.

Примеры синтаксиса

' Процедура. Ничего не возвращает
' Перегрузка в VBA отсутствует
Sub foo(a As String, b As String)
    ' Exit Sub ' Это значит "выйти из процедуры"
    MsgBox a + ";" + b
End Sub' Функция. Вовращает Integer
Function LengthSqr(x As Integer, y As IntegerAs Integer
    ' Exit Function
    LengthSqr = x * x + y * y
End FunctionSub FormatPrice()
    Dim s1 As String, s2 As String
    s1 = "str1"
    s2 = "str2"
    If s1 <> s2 Then
        foo "123""456" ' Скобки при вызове процедур запрещены
    End IfDim res As sTRING ' Регистр в VB не важен. Впрочем, редактор Вас поправит
    Dim i As Integer
    ' Цикл всегда состоит из нескольких строк
    For i = 1 To 10
        res = res + CStr(i) ' Конвертация чего угодно в String
        If i = 5 Then Exit For
    Next iDim x As Double
    x = Val("1.234"' Парсинг чисел
    x = x + 10
    MsgBox xOn Error Resume Next ' Обработка ошибок - игнорировать все ошибки
    x = 5 / 0
    MsgBox xOn Error GoTo Err ' При ошибке перейти к метке Err
    x = 5 / 0
    MsgBox "OK!"
    GoTo ne

Err:
    MsgBox 

"Err!"

ne:

On Error GoTo 0 ' Отключаем обработку ошибок

    ' Циклы бывает, какие захотите
    Do While True
        Exit DoLoop 'While True
    Do 'Until False
        Exit Do
    Loop Until False
    ' А вот при вызове функций, от которых хотим получить значение, скобки нужны.
    ' Val также умеет возвращать Integer
    Select Case LengthSqr(Len("abc"), Val("4"))
    Case 24
        MsgBox "0"
    Case 25
        MsgBox "1"
    Case 26
        MsgBox "2"
    End Select' Двухмерный массив.
    ' Можно также менять размеры командой ReDim (Preserve) - см. google
    Dim arr(1 to 10, 5 to 6) As Integer
    arr(1, 6) = 8Dim coll As New Collection
    Dim coll2 As Collection
    coll.Add "item""key"
    Set coll2 = coll ' Все присваивания объектов должны производится командой Set
    MsgBox coll2("key")
    Set coll2 = New Collection
    MsgBox coll2.Count
End Sub

Грабли-1. При копировании кода из IDE (в английском Excel) есь текст конвертируется в 1252 Latin-1. Поэтому, если хотите сохранить русские комментарии — надо сохранить крокозябры как Latin-1, а потом открыть в 1251.

Грабли-2. Т.к. VB позволяет использовать необъявленные переменные, я всегда в начале кода (перед всеми процедурами) ставлю строчку Option Explicit. Эта директива запрещает интерпретатору заводить переменные самостоятельно.

Грабли-3. Глобальные переменные можно объявлять только до первой функции/процедуры. Локальные — в любом месте процедуры/функции.

Еще немного дополнительных функций, которые могут пригодится: InPos, Mid, Trim, LBound, UBound. Также ответы на все вопросы по поводу работы функций/их параметров можно получить в MSDN.

Надеюсь, что этого Вам хватит, чтобы не пугаться кода и самостоятельно написать какое-нибудь домашнее задание по информатике. По ходу поста я буду ненавязчиво знакомить Вас с новыми конструкциями.

Кодим много и под Excel

В этой части мы уже начнём кодить нечто, что умеет работать с нашими листами в Excel. Для начала создадим отдельный лист с именем result (лист с данными назовём data). Теперь, наверное, нужно этот лист очистить от того, что на нём есть. Также мы «выделим» лист с данными, чтобы каждый раз не писать длинное обращение к массиву с листами.

Sub FormatPrice()
    Sheets("result").Cells.Clear
    Sheets("data").Activate
End Sub

Работа с диапазонами ячеек

Вся работа в Excel VBA производится с диапазонами ячеек. Они создаются функцией Range и возвращают объект типа Range. У него есть всё необходимое для работы с данными и/или оформлением. Кстати сказать, свойство Cells листа — это тоже Range.

Примеры работы с Range

Sheets("result").Activate
Dim r As Range
Set r = Range("A1")
r.Value = "123"
Set r = Range("A3,A5")
r.Font.Color = vbRed
r.Value = "456"
Set r = Range("A6:A7")
r.Value = "=A1+A3"

Теперь давайте поймем алгоритм работы нашего кода. Итак, у каждой строчки листа data, начиная со второй, есть некоторые данные, которые нас не интересуют (ID, название и цена) и есть две вложенные группы, к которым она принадлежит (тип и производитель). Более того, эти строки отсортированы. Пока мы забудем про пропуски перед началом новой группы — так будет проще. Я предлагаю такой алгоритм:

  1. Считали группы из очередной строки.
  2. Пробегаемся по всем группам в порядке приоритета (вначале более крупные)
    1. Если текущая группа не совпадает, вызываем процедуру AddGroup(i, name), где i — номер группы (от номера текущей до максимума), name — её имя. Несколько вызовов необходимы, чтобы создать не только наш заголовок, но и всё более мелкие.
  3. После отрисовки всех необходимых заголовков делаем еще одну строку и заполняем её данными.

Для упрощения работы рекомендую определить следующие функции-сокращения:

Function GetCol(Col As IntegerAs String
    GetCol = Chr(Asc("A") + Col)
End FunctionFunction GetCellS(Sheet As String, Col As Integer, Row As IntegerAs Range
    Set GetCellS = Sheets(Sheet).Range(GetCol(Col) + CStr(Row))
End FunctionFunction GetCell(Col As Integer, Row As IntegerAs Range
    Set GetCell = Range(GetCol(Col) + CStr(Row))
End Function

Далее определим глобальную переменную «текущая строчка»: Dim CurRow As Integer. В начале процедуры её следует сделать равной единице. Еще нам потребуется переменная-«текущая строка в data», массив с именами групп текущей предыдущей строк. Потом можно написать цикл «пока первая ячейка в строке непуста».

Глобальные переменные

Option Explicit ' про эту строчку я уже рассказывал
Dim CurRow As Integer
Const GroupsCount As Integer = 2
Const DataCount As Integer = 3

FormatPrice

Sub FormatPrice()
    Dim I As Integer ' строка в data
    CurRow = 1
    Dim Groups(1 To GroupsCount) As String
    Dim PrGroups(1 To GroupsCount) As String

    Sheets(

"data").Activate
    I = 2
    Do While True
        If GetCell(0, I).Value = "" Then Exit Do
        ' ...
        I = I + 1
    Loop
End Sub

Теперь надо заполнить массив Groups:

На месте многоточия

Dim I2 As Integer
For I2 = 1 To GroupsCount
    Groups(I2) = GetCell(I2, I)
Next I2
' ...
For I2 = 1 To GroupsCount ' VB не умеет копировать массивы
    PrGroups(I2) = Groups(I2)
Next I2
I =  I + 1

И создать заголовки:

На месте многоточия в предыдущем куске

For I2 = 1 To GroupsCount
    If Groups(I2) <> PrGroups(I2) Then
        Dim I3 As Integer
        For I3 = I2 To GroupsCount
            AddHeader I3, Groups(I3)
        Next I3
        Exit For
    End If
Next I2

Не забудем про процедуру AddHeader:

Перед FormatPrice

Sub AddHeader(Ty As Integer, Name As String)
    GetCellS("result", 1, CurRow).Value = Name
    CurRow = CurRow + 1
End Sub

Теперь надо перенести всякую информацию в result

For I2 = 0 To DataCount - 1
    GetCellS("result", I2, CurRow).Value = GetCell(I2, I)
Next I2

Подогнать столбцы по ширине и выбрать лист result для показа результата

После цикла в конце FormatPrice

Sheets("Result").Activate
Columns.AutoFit

Всё. Можно любоваться первой версией.

Некрасиво, но похоже. Давайте разбираться с форматированием. Сначала изменим процедуру AddHeader:

Sub AddHeader(Ty As Integer, Name As String)
    Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow)).Merge
    ' Чтобы не заводить переменную и не писать каждый раз длинный вызов
    ' можно воспользоваться блоком With
    With GetCellS("result", 0, CurRow)
        .Value = Name
        .Font.Italic = True
        .Font.Name = "Cambria"
        Select Case Ty
        Case 1 ' Тип
            .Font.Bold = True
            .Font.Size = 16
        Case 2 ' Производитель
            .Font.Size = 12
        End Select
        .HorizontalAlignment = xlCenter
    End With
    CurRow = CurRow + 1
End Sub

Уже лучше:

Осталось только сделать границы. Тут уже нам требуется работать со всеми объединёнными ячейками, иначе бордюр будет только у одной:

Поэтому чуть-чуть меняем код с добавлением стиля границ:

Sub AddHeader(Ty As Integer, Name As String)
    With Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow))
        .Merge
        .Value = Name
        .Font.Italic = True
        .Font.Name = "Cambria"
        .HorizontalAlignment = xlCenterSelect Case Ty
        Case 1 ' Тип
            .Font.Bold = True
            .Font.Size = 16
            .Borders(xlTop).Weight = xlThick
        Case 2 ' Производитель
            .Font.Size = 12
            .Borders(xlTop).Weight = xlMedium
        End Select
        .Borders(xlBottom).Weight = xlMedium ' По убыванию: xlThick, xlMedium, xlThin, xlHairline
    End With
    CurRow = CurRow + 1
End Sub

Осталось лишь добится пропусков перед началом новой группы. Это легко:

В начале FormatPrice

Dim I As Integer ' строка в  data
CurRow = 0 ' чтобы не было пропуска в самом начале
Dim Groups(1 To GroupsCount) As String

В цикле расстановки заголовков

If Groups(I2) <> PrGroups(I2) Then
    CurRow = CurRow + 1
    Dim I3 As Integer

В точности то, что и хотели.

Надеюсь, что эта статья помогла вам немного освоится с программированием для Excel на VBA. Домашнее задание — добавить заголовки «ID, Название, Цена» в результат. Подсказка: CurRow = 0 CurRow = 1.

Файл можно скачать тут (min.us) или тут (Dropbox). Не забудьте разрешить исполнение макросов. Если кто-нибудь подскажет человеческих файлохостинг, залью туда.

Спасибо за внимание.

Буду рад конструктивной критике в комментариях.

UPD: Перезалил пример на Dropbox и min.us.

UPD2: На самом деле, при вызове процедуры с одним параметром скобки можно поставить. Либо использовать конструкцию Call Foo(«bar», 1, 2, 3) — тут скобки нужны постоянно.

VBA (Visual Basic for Applications) is a programming language that empowers you to automate almost every in Excel. With VBA, you can refer to the Excel Objects and use the properties, methods, and events associated with them. For example, you can create a pivot table, insert a chart, and show a message box to the user using a macro.

what-is-vba

The crazy thing is:

For all the tasks which you perform manually in minutes, VBA can do it in seconds, with a single click, with the same accuracy. Even you can write VBA codes that can run automatically when you open a document, a workbook, or even at a specific time.

Let me show you a real-life example:

Every morning when I go to the office, the first thing I need to do is to create a pivot table for the month-to-date sales and present it to my boss. This includes the same steps, every day. But when I realized that I can use VBA to create a pivot table and insert it in a single click, it saved me 5 minutes every day.

Macro Codes To Create A Pivot Table

Note: VBA is one of the Advanced Excel Skills.

How VBA Works

VBA is an Object-Oriented Language and as an object-oriented language, in VBA, we structure our codes in a way where we are using objects and then defining their properties.

In simple words, first, we define the object and then the activity which we want to perform. There are objects, collections, methods, and properties which you can use in VBA to write your code.

how-vba-works

[icon name=”bell” class=””] Don’t miss this: Let’s say you want to tell someone to open a box. The words you will use would be “Open the Box”. It’s plain English, Right? But when it comes to VBA and writing a macro this will be:

Box.Open

As you can see, the above code is started with the box which is our object here, and then we have used the method “Open” for it. Let’s go a bit specific, let say if you want to open the box which is RED in color. And for this the code will be:

Boxes(“Red”).Open

In the above code, boxes are the collection, and open is the method. If you have multiple boxes we are defining a specific box here. Here’s another way:

Box(“Red”).Unlock = True

In the above code, again boxes are the collection, and Unlock is the property that is set to TRUE.

What is VBA used for in Excel?

In Excel, you can use VBA for different things. Here are a few:

  • Enter Data: You can enter data in a cell, range of cells. You can also copy and paste data from one section to another.
  • Task Automation: You can automate tasks that want you to spend a lot of time. The best example I can give is using a macro to create a pivot table.
  • Create a Custom Excel Function: With VBA, you can also create a Custom User Defined Function and use it in the worksheet.
  • Create Add-Ins: In Excel, you can convert your VBA codes into add-ins and share them with others as well.
  • Integrate with other Microsoft Applications: You can also integrate Excel with other Microsoft applications. Like, you can enter data into a text file.

Excel Programming Fundamentals

A procedure in VBA is a set of codes or a single line of code that performs a specific activity.

  1. SUB: Sub procedure can perform actions but doesn’t return a value (but you can use an object to get that value).
  2. Function: With the help of the Function procedure, you create your function, which you can use in the worksheet or the other SUB and FUNCTION procedures (See this: VBA Function).

2. Variables and Constants

You need variables and constants to use values in the code multiple times.

  • Variable: A Variable can store a value, it has a name, you need to define its data type, and you can change the value it stores. As the name suggests, “VARIABLE” has no fixed value. It is like a storage box that is stored in the system.
  • Constant:‌ A constant also can store a value, but you can’t change the value during the execution of the code.

3. Data Types

You need to declare the data type for VARIABLES and CONSTANTS.

define data type

When you specify the data type for a variable or a constant, it ensures the validity of your data. If you omit the data type, VBA applies the Variant data type to your variable (it’s the most flexible), VBA won’t guess what the data type should be.

Tip: VBA Option Explicit

4. Objects, Properties, and Methods

Visual Basic for Applications is an Object-Oriented language, and to make the best out of it; you need to understand Excel Objects.

The workbook you use in Excel has different objects, and with all those objects, there are several properties that you can access and methods that you can use.

5. Events

Whenever you do something in Excel, that’s an event: enter a value in a cell, insert a new worksheet, or insert a chart. Below is the classification of events based on the objects:

  1. Application Events: These are events that are associated with the Excel application itself.
  2. Workbook Events: These are events that are associated with the actions that happen in a workbook.
  3. Worksheet Events: These events are associated with the action that happens in a worksheet.
  4. Chart Events: These events are associated with the chart sheets (which are different from worksheets).
  5. Userform Events: These events are associated with the action that happens with a user form.
  6. OnTime Events: OnTime events are those which can trigger code at a particular point in time.
  7. OnKey Events: OnKey events are those which can trigger code when a particular key is pressed.

6. Range

The range object is the most common and popular way to refer to a range in your VBA codes. You need to refer to the cell address, let me tell you the syntax.

Worksheets(“Sheet1”).Range(“A1”)

7. Conditions

Just like any other programming language, you can also write codes to test conditions in VBA. It allows you to do it in two different ways.

  • IF THEN‌ ELSE‌: It’s an IF statement that you can use to test a condition and then run a line of code if that condition is TRUE. You can also write nesting conditions with it
  • SELEC‌T‌ CASE: In the select case, you can specify a condition and then different cases for outcomes to test to run different lines of code to run. It’s a little more structured than the IF statement.

8. VBA Loops

You can write codes that can repeat and re-repeat an action in VBA, and there are multiple ways that you can use to write code like this.

  • For Next: The best fit for using For Next is when you want to repeat a set of actions a fixed number of times.
  • For Each Next: It’s perfect to use when you want to loop through a group of objects from a collection of objects.
  • Do While Loop: The simple idea behind the Do While Loop is to perform an activity while a condition is true.
  • Do Until Loop: In the Do Until, VBA runs a loop and continues to run it if the condition is FALSE.

9. Input Box and Message Box

  • Input Box: The input Box is a function that shows an input box to the user and collects a response.
  • Message Box: Message Box helps you show a message to the user but, you have an option to add buttons to the message box to get the response of the user.

10. Errors

Excel has no luck when it comes to programming errors, and you have to deal with them, no matter what.

  1. Syntax Errors: It’s like typos that you do while writing codes, but VBA can help you by pointing out these errors.
  2. Compile Errors: It comes when you write code to perform an activity, but that activity is not valid.
  3. Runtime Errors: A RUNTIME error occurs at the time of executing the code. It stops the code and shows you the error dialog box.
  4. Logical Error: It’s not an error but a mistake while writing code and sometimes can give you nuts while finding and correcting them.

Write a Macro (VBA Program) in Excel

I have a strong belief that in the initial time when someone is starting programming in Excel, HE/SHE should write more and more codes from scratch. The more codes you write from scratch, the more you understand how VBA works.

But you need to start with writing simple codes instead of jumping into complex ones. That’s WHY I don’t want you to think about anything complex right now.

You can even write a macro code to create a pivot table, but right now, I don’t want you to think that far. Let’s think about an activity that you want to perform in your worksheet, and you can write code for it.

  1. Go to the Developer Tab and open the Visual Basic Editor from the “Visual Basic” button.
    1-visual-basic-button
  2. After that, insert a new module from the “Project Window” (Right-click ➢ Insert ➢ Module).
    2-insert-a-new-module
  3. After that, come to the code window and create a macro with the name “Enter Done” (we are creating a SUB procedure), just like I have below.
    3-code-window
  4. From here, you need to write a code which we have just discussed above. Hold for second and think like this: You need to specify the cell where you want to insert the value and then the value which you wish to enter.
  5. Enter the cell reference, and for this, you need to use RANGE object and specify the cell address in it, like below:
    4-cell-reference-range-object
  6. After that, enter a dot, and the moment you add a dot, you’ll have a list of properties that you can define and activities that you can do with the range.
    5-enter-a-dot
  7. From here, you need to select the “Value” property and set the text which you want to insert in the cell “A1” and when to do it, your code with look something like below.
    6-select-value
  8. Finally, above the line of code, enter the text (‘this code enters the value “Done” in the cell A5). It’s a VBA Comment that you can insert to define the line of code that you have written.
    7-enter-the-text-above-line-code
Sub Enter_Done()
'this code enters the value “Done” in the cell A5
Range("A1").Value = "Done"
End Sub

Let’s understand this…

You can split this code into two different parts.

  • In the FIRST part, we have specified the cell address by using the RANGE object. And, to refer to a cell using a range object you need to wrap the cell address with double quotes (you can also use square brackets).
  • In the SECOND part, we have specified the value to enter into the cell. What you have done is, you have defined the value property for cell A5 by using “.Value”. After that, the next thing that you have specified is the value against the value property. Whenever you are defining a value (if it’s text), you need to wrap that value inside double quotation marks.

Here I have listed some of the most amazing tutorials (not in any particular sequence) that can help you learn VBA in NO TIME.

Excel VBA Tutorial about essential terms to learnSo you’ve created your first (or your first few) Excel macro(s), perhaps by following these 7 easy steps to create a macro. By now, your colleagues are already looking at you like you’re a wizard.

That is a great sign that you’re on a good way to learning macros and Visual Basic for Applications (VBA).

However…

Being able to create a basic macro in Excel is only the beginning in the process to become a really efficient and productive user of macros and VBA. If you really want to unleash the power of these tools, you must learn VBA due to the fact that, among others, recording a macro sometimes simply doesn’t “cut it”.

The bad news (at least for some of you) is that using VBA requires that you learn programming.

The good news is that programming in Excel is not as difficult as it may sound at first.

If this doesn’t sound that convincing, wait…

In order to help you during the process of learning Visual Basic for Applications, I have created this Excel VBA tutorial for beginners where I explain, in detail, 16 (actually you’ll probably learn even more) essential terms you need to know in order to learn VBA programming. In particular, I focus on the basic terms that you will constantly find during the process of becoming a VBA expert.

By the time you’re done reading this beginners guide, you will understand the basics of at least 16 essential terms you need to know to learn Visual Basic for Applications. The following is the outline for this Excel tutorial:

This Excel VBA Tutorial for Beginners is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Tutorial for Beginners workbook examples

If some (or all) of the terms above sound completely strange to you, don’t worry. Before learning VBA, I studied and worked in 2 careers that are infamous for using specialized jargon that is completely incomprehensible to outsiders: law and finance. To make a long story short…Visual Basic for Applications still seemed to me like a completely different language. But then I realized something:

VBA is indeed a different language and, after some time, I realized is not that hard to learn. This brings me to the first question I cover in this Excel VBA tutorial for beginners…

What Is VBA?

As you may already know, VBA stands for Visual Basic for Applications.

VBA is a programming language which was developed by Microsoft and is included in most products that are part of Microsoft Office.

What does this mean exactly?

You can think of a programming language just as you would think of pretty much any other language: English, Spanish, German, French, Italian, Portuguese, Hindi, Mandarin Chinese, Korean, etc. A language has several functions but, for purposes of this Excel VBA tutorial for beginners, I focus on one aspect: Communication.

Programming languages are slightly different in that you generally don’t use them to communicate with a human being. You use a programming language, such as VBA, to communicate with a computer. More particularly, you communicate instructions to the computer.

In other words, Visual Basic for Applications is the language that allows you and me to communicate instructions to Excel.

So there is no way around it:

In order to be able to automate tasks in Excel and unleash its power, you must learn VBA. However, as you may expect, VBA is different from regular human languages.

More generally, the codes you can use to communicate with your computer are slightly different from those you use to communicate with other people. One of the main reasons for this is that, despite the recent advances, computers can’t fully deal with or handle certain human communication features. These include, for example, human facial and body expressions.

Imagine you are learning a new human language (such as French, Italian or Spanish). One of the subject you need to study is its structure and, quite likely, you come across terms such as nouns, pronouns, verbs, adjectives, and the like. If you hadn’t heard those terms before or you’re like me and forgot their precise meanings, learning a new language could be quite challenging.

Well…

Programming languages are not significantly different and, therefore, in order to learn a language such as Visual Basic for Applications, you need to understand its structure. Since this structure isn’t exactly the same as that of human languages, you encounter some special (and different) terms that you must learn.

And this is where this Excel VBA tutorial for beginners comes in to help. In the following sections, I explain to you some of the most important terms that you need to know to learn VBA programming. By the end of this guide, you will understand the basic building blocks of Visual Basic for Applications, which will allow you to learn this programming language and become fluent much faster.

You can, to a certain extent, make an analogy between some of the word classes (nouns, verbs, adverbs, etc.) in English and some of the components of VBA to help you understand these elements better. In this Excel VBA tutorial for beginners, I use the analogy between VBA components and parts of speech to a certain extent but, where appropriate, I use different illustrations.

What Is A Macro? The Difference Between Macros And VBA?

Excel macros and Visual Basic for Applications are not exactly the same thing, although they are closely related and, sometimes, people use them interchangeably.

As explained above, VBA is a programming language which can be used in several programs that are part of Microsoft Office such as Excel, Power Point, Word and Access.

A macro is:

  • Not a programming language.
  • (Usually) Defined as a set of instructions you use to automate a Microsoft Office application (such as Excel).

In other words:

  • A macro is the sequence of instructions that you want Excel to follow in order to achieve a particular purpose.
  • Visual Basic for Applications is a programming language you can use to create macros.

Take, for example, the following instructions:

Example of difference between macros and visual basic for applications

The whole set of instructions is the equivalent of an Excel macro. It’s a sequence of instructions that should be followed in order to achieve a purpose which, in this case, is enjoying a tsukemen meal.

The language in which the instructions in the image above are written is English. This is the equivalent of Visual Basic for Applications.

So… as you can see: VBA and Excel macros have a very close relationship but, strictly speaking, they are not the same.

However, as you will see below, it is not uncommon to use certain terms interchangeably with the word macro.

What Is VBA Code?

This is where it may start to get a little bit confusing, but please bear with me…

When working with VBA, you execute VBA code. This VBA code carries out (certain) actions/tasks. You can generate VBA code in one of the following 2 ways:

  • By recording certain actions you perform in an Excel workbook by using the macro recorder.
  • By writing the VBA code in the Visual Basic Editor (VBE).

The following is a very basic example of VBA code. The comments near the top (in green font) explain what the piece of code does.

Example of VBA code

Now, you may wonder… what is the difference between a macro and VBA code?

I don’t go into too may details (it deviates from the purpose of this Excel VBA tutorial for beginners). For purposes of this guide, there is no essential difference. In fact, in the context of several Microsoft Office applications, the term “macro” is used by several users to refer to VBA code.

Some Excel VBA users distinguish between code and macros. From this perspective:

  • The term “VBA code” (usually) refers to the set of VBA commands you create by either:
    • Recording a macro; or
    • Writing VBA code in the VBE.
  • The term “macro” (usually) refers to the set of instructions Excel executes automatically.

Now that the definitions of macros, VBA and VBA code are clear (or at least clearer than they were at the beginning), let’s start looking at the different components of Visual Basic for Applications.

What Is A Module?

In broad terms, a module is the equivalent of a VBA container. In other words, it is where Excel actually stores the VBA code.

If you have seen a cargo ship or port, or if you have ever been involved in shipping, you may have seen intermodal containers (such as the ones in the image below). These containers are used for, among other purposes, storing goods.

Containers used as analogy for modules in VBA

In Excel, the equivalent of the intermodal containers are modules and the goods that are stored are the pieces of VBA code.

You can check out which modules are stored in the Excel workbook you’re currently working on in the Project Explorer (which is one of the sections of the Visual Basic Editor). The following screenshot shows an example of the Project Explorer, where there is only 1 standard module (called “Module1”).

project explorer with module

Standard modules are also referred to simply as modules. There are other types of modules in addition to standard modules.

Modules are made out of procedures so, as you can imagine, the next logical question is…

What Are Procedures And Routines?

A procedure is, basically, the part of a computer program that performs a particular task or action.

In more technical terms, a procedure is a block of statements that is enclosed by a particular declaration statement and an End declaration. VBA supports two types of procedures:

  • Sub procedures, which perform an action in Excel. The declaration statement that begins a Sub procedure is “Sub”.

    For example, the following piece of VBA code (the comments near the top of the image describe its basic purpose) is a Sub procedure. Notice the opening declaration statement, the matching End declaration and how the block of statements is enclosed by these two declarations.

    Example of a sub procedure with declaration and end statement

  • Function procedures, which carry out calculations and return a value.

Sub procedures do not return a value but function procedures can perform certain activities before returning a value.

The practical use of terms such as sub procedure, routine, program, procedure and macro can be a little bit confusing. In some cases, these terms are used interchangeably.

Perhaps the most important distinction you should be able to make is between Sub and Function procedures, as explained above. You can refer to these tutorials on Sub procedures and Function procedures for further information.

I imagine that you may have several questions related to the (more technical) definition of procedure given above, so let’s take a look at the meaning of one of its key words…

What Is A Statement?

A statement is an instruction. In some contexts, you can distinguish 2 main types of statements:

  1. Declaration statements are, as implied by their name, used to declare something such as a variable or a constant.

    When defining what a Sub procedure is, I showed you an example of a declaration statement. In this particular case, this declaration statement is the opening Sub statement which declares the Sub procedure named Best_Excel_Tutorial.

    Example of a declaration statement in VBA code

  2. Executable statements are statements that specify that a particular action should be taken.

    The Best_Excel_Tutorial macro used as an example above has several executable statements. For example, the statement “ActiveCell.Select” specifies that Excel should select the current active cell.

    Example of an executable statement in VBA code

    A special type of executable statements are assignment statements. Assignment statements assign a particular value or expression to a variable or constant.

What Are Objects?

As you’ve seen above, procedures perform tasks or actions.

You may wonder, what is the object of those tasks? In other words, on what is Excel performing the particular action?

The answer is objects.

Consider English grammar.

  • In regular English, an object (usually) has something done to/with it.
  • In real life, you can find objects anywhere, including the laptop that you use to work on Excel.

Analogy to explain what is an object in VBA

Horses are another example of objects.

Example of an object in Visual Basic for Applications

Actually, since I used to be a real big fan of horses when I was a child, I use them for explanation purposes throughout this Excel VBA tutorial for beginners and have some more horse pictures throughout this guide.

In Visual Basic for Applications things are not very different. This is because most VBA code works with (and manipulates) objects. In the context of Excel VBA, you can work with more than 100 objects.

The following are some examples of objects in Visual Basic for Applications:

  • Workbooks.
  • Worksheets.
  • Cell ranges.
  • Cells.
  • Cell fonts.

Can you spot 2 objects in the Best_Excel_Tutorial macro that has been used as an example?

If you haven’t, don’t worry; I point them out for you in the following screenshot.

Example of two objects in a piece of VBA code

The ActiveCell and Selection objects which I highlight above are among the most common.

  • ActiveCell refers to the current active cell in the current active Excel workbook.
  • Selection refers to the currently selected object which, in the example above, is a cell.

Objects are defined by classes, so the next question is…

What Are Classes?

As I mention above, classes define objects and, more particularly, classes define the following aspects of an object:

  • Variables.
  • Properties.
  • Procedures.
  • Events.

As a consequence of the above, you can:

  • Think of objects as instances of classes; or
  • (Similarly)Think about classes as blueprints.

For example, let’s assume you used to run a company that produced roll film cameras. That company had a basic blueprint or technical drawing such as the following:

Blueprint analogy to explain difference between classes and objects in VBA

This blueprint defines the characteristics of each of the roll film cameras to be produced and is, therefore, the equivalent of a VBA class. Once the company has the blueprint, it can produce the actual cameras.

Analogy explaining distinction between classes and objects

The actual produced cameras are the equivalent of a VBA object.

Classes are a slightly advanced Excel topic and, therefore, you’re unlikely to work much with them at the beginning. But, just in case, now you know what a class is and how it is different from, and related to, an object.

What Are Collections?

In Visual Basic for Applications, the word collection refers to collections of objects.

At the basic level, the general use of the word collection doesn’t differ too much from the use given to it in VBA. As you’d expect, in very general terms, a collection is a group of objects, more precisely a group of related objects.

Therefore, you can use collections to group and manage objects that are related between them.

At a basic level, the concept of collections is relatively simple but, if you want a more graphical illustration, check out the following Dr. Seuss collection.

Analogy of a collection of objects in VBA

In the context of VBA:

  • Collections are objects.
  • There is (also) a collection class.

If collections group objects that have some relationship between them, you may be wondering…

How Are Objects Related To Each Other?

Objects can be related to each other in several ways. However, the main type of relationship is of containment.

Containment relationships are present when objects are put within a container object. This means that objects can contain other objects within them, such as the plastic container (an object) that holds the Dr. Seuss books (other objects) in the image above.

A very good example of a containment relationship is a collection of objects.

Another important type of relationship is hierarchical, which is mostly applicable to classes. Hierarchical relationships occur when a class is derived from a more fundamental class.

What Is A Property?

Objects have properties. These are the attributes, characteristics or qualities that can be used to describe the object. I cover the topic of properties in this Excel tutorial.

VBA allows you to do both of the following:

  • Read the current value of an object’s properties; and
  • Change an object’s properties.

Let’s take, for example, this horse:

Example of VBA object properties

What are some of its properties? How about the color of its hair or its eyes? The size of its ears?

You get the idea.

In addition to having properties, objects have methods. As you may expect, the next question I answer is…

What Are Methods?

To understand what methods are, let’s go back to English grammar.

As I explain above when defining the term “object”, an object has something done to it. The method is the “something” which is done to the object. In other words: A method expresses an action performed with/on an object.

In grammatical terms, a method (in VBA) is roughly the equivalent of a verb (in English). I cover the topic of methods in more detail here.

Let’s continue using horses to illustrate the meaning of these Visual Basic for Applications components:

What is an example of a method (verb) that could be applied to a horse?

How about horseback riding?

Illustration of VBA methods in Excel

How Do Properties And Methods Look Like In Excel?

Let’s go back to the Best_Excel_Tutorial macro that I have been using as an example in this particular guide for beginners. If you run that macro, Excel does the following:

  • Types “This is the best Excel tutorial” into the active cell.
  • Auto-fits the column width of the active cell.
  • Colors the active cell red.
  • Changes the font color of the active cell to blue.

Example of a macro changing the properties of cells in Excel

Now that you know what is a property and what is a method:

Would you be able to distinguish which of the above make reference to a property and which to a method?

To answer this question, let’s take a look again at the VBA code:

example of Visual Basic for Applications code

And let’s take a closer look at the relevant lines to determine whether they make reference to a property or a method:

  • “ActiveCell.FormulaR1C1 = “This is the best Excel tutorial”” tells Excel to write “This is the best Excel tutorial” in the active cell.

    FormulaR1C1 as a property in Visual Basic for Applications
    ActiveCell returns an object. More precisely, it returns the current active cell.

    So what is FormulaR1C1? A property or a method?

    Property. More precisely, Formula R1C1 sets the formula for ActiveCell.

  • “Selection.Columns.AutoFit” instructs Excel to auto-fit the column of the active cell.

    Example of AutoFit as a method in Visual Basic for Applications
    In this case, the object is represented by Selection.Columns which represents the column of the current active cell.

    So what is the remaining part of the statement? Is AutoFit a property or a method?If you answered method, you are correct. AutoFit is changing the width of the relevant column to achieve the best fit. In other words, is doing something (auto-fitting) to the object.

  • The part of the first With… End With statement that actually sets the fill color of the active cell is “.Color = 255”.

    Example of the color property in Visual Basic for Applications
    All the individual statements within this With… End With statement (including “.Color = 255”) refer to Selection.Interior. This is the interior of the current selection (in this case, the active cell).

    You know which question is coming:

    Is Color a property or a method?Since Color is setting the main color of the interior of the active cell, the answer is property.

  • Finally, the part of the second With… End With Statement that determines the font color is “.Color = –4165632”.

    Another example of the Color property in VBA
    This is, for purposes of this Excel VBA tutorial for beginners, substantially the same case as above. In this case reference is made to Selection.Font which, in this example, is the font of the text in the active cell.

    And, as you already know that Color is a property, I won’t ask you again 😉 .

What Are Variables And Arrays?

In computer science, a variable is a storage location that you pair with a name and use to represent a particular value. That value is stored in the computer’s memory.

In other words: You use variables as placeholders for particular values. You can think about variables as envelopes.

Analogy used to illustrate concept of variables in Visual Basic for Applications

How can you use envelopes to store information?

You can, for example:

  • Put some information inside an envelope. This is the content of the envelope or, for programming purposes, the value of the variable.
  • Put a name to the envelope. This is the name of the envelope or variable.

Now, let’s imagine that you need to tell somebody to get the information that is inside a particular envelope. You can describe the information that you need in either of the following ways:

  • By describing the information itself. In this case, the person that is helping you has to open each and every envelope to check out their contents.
  • By mentioning the name of the relevant envelope. In this case, the person helping you doesn’t need to open each envelope to know where the piece of information they need to get is.

Can you picture why referring to the name of the envelope, instead of the information itself, can be a more efficient option?

But let’s get back to the topic that really matters:

Horses!

I bet you were not expecting that 😛 … but let’s imagine that you own one of the horses in the images above and a very important part of your horse’s diet is sugar cubes.

Image used to explain concept of variables in Visual Basic for Applications

The horse has 5 different caretakers and, each day, he should eat between 5 and 10 sugar cubes. In order to guarantee that this is the case, you set the following rule: each caretaker should give 1 or 2 sugar cubes per day to the horse.

At the beginning of each day, each caretaker needs to report how many sugar cubes he has given to the horse the day before. This report is done by filling the following Excel table.

Table used to explain VBA variables

Since you are a very efficient manager, you want to program a VBA application (let’s call it “Horse_Sugar_Cubes”) that does the following:

  • Asks each caretaker how many sugar cubes they have given to the horse.
  • If any of the caretakers has not followed the rule that requires him to give 1 or 2 sugar cubes to the horse, issues a reminder.

Before we take a look at the actual VBA code, check out how the Horse_Sugar_Cubes macro works in practice:

Example of how VBA application will run in Excel

This Excel VBA Tutorial for Beginners is accompanied by Excel workbooks containing the data and macros I use (including the Horse_Sugar_Cubes macro). You can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Tutorial for Beginners workbook examples

Let’s start the set up of the Horse_Sugar_Cubes application. For these purposes, you may want to use the following two variables:

  • A variable that stores the number of sugar cubes given by a particular caretaker to the horse. You can name this variable sugarCubes.
  • A variable that stores the identification number of the caretaker. You can name this variable caretakerNumber.

How do you create these variables?

To create a variable in Visual Basic for Applications, you must declare it. When you declare a variable, you determine what is the name and what are the characteristics of the particular variable, and tell the computer to allocate some storage space.

You declare a variable in VBA by using the Dim statement. I explain the topic of variable declaration in this Excel tutorial. For the moment, bear in mind the following:

  • You can declare variables at different levels. The level at which you declare a variable determines when is the variable applicable.

    For example, you can declare a variable at the top of a module. This variable is known as a module-level variable and exists as long as the module is loaded. Additionally, they’re available for use in any procedure within the relevant module.

    You can also create a variable with a more limited reach, by declaring the variable within a procedure. In this case, this variable is known as a procedure-level variable. Procedure-level variables can only be used within the relevant procedure in which they have been declared.

  • Since you use variables to store different types of data, you can define different types for a variable. You do this by using the As keyword.

    Some examples of types that you can specify for a variable are Integer, Boolean, String and Range.

Let’s take a look at how you can declare the variables caretakerNumber and sugarCubes in practice.

Example of how to declare a variable in Visual Basic for Applications

I come back to the topic of variables further down this Excel VBA tutorial for purposes of explaining how you can use variables in the VBA macro to help you keep track of how many sugar cubes are given to the horse each day.

As a final note, allow me to make a brief introduction of arrays. I provide a more detailed introduction to arrays in this VBA tutorial.

Variables that contain a single value are known as scalar variables. You use scalar variables when working with a single item.

What do you do if you are working with a group of items that are related to each other?

In these cases, you use arrays. Arrays are sets of indexed elements that share the same data type and have a logical relationship between them. The function is substantially the same as that of a variable: holding values. The main difference is that arrays can store several values while scalar variables can hold only one value.

When you use an array, you refer to the different elements of the array using the common name and distinguish among them with a number (called a subscript or index). For example, if you had a group of 10 horses numbered 1 through 10, you can refer to them as horses(1), horses(2), horses(3) and so on until horses(10).

Example of an array in Visual Basic for Applications

Let’s continue with the study of the main VBA components that appear in the Horse_Sugar_Cubes application by understanding…

What Is A Condition?

A condition is a statement or expression that evaluates to either true or false. Then, depending on whether the statement has evaluated to true or false, Excel executes (or doesn’t execute) a group of statements. In other words: If the condition is met (true), something happens.

Can you think of a way you can apply a conditional statement in the VBA application you are developing to keep track of how many sugar cubes are given to your horse by the caretakers?

Hint: conditional statements often use the if-then structure.

If you take a close look at the description of the 2 things that the Horse_Sugar_Cubes application should do, you’ll notice that the second step follows the if-then structure. More precisely:

  • If any of the caretakers doesn’t follow the rule that requires him to give 1 or 2 sugar cubes to the horse…
  • Then the Horse_Sugar_Cubes macro issues a reminder.

If you’re an Excel user, you may have noticed that conditions are not exclusive to VBA programming. For example, several Excel functions such as the IF function allow you to check whether a condition is true or not and, based on the result, do one thing or another. Additionally, you can use other functions such as ISNUMBER to perform logical tests.

There are several ways to structure conditional statements in Visual Basic Applications. For purposes of the Horse_Sugar_Cubes application, you can use an If…Then…Else statement.

How does this look inside the Visual Basic Editor?

You can use set up the following If…Then statement for the Horse_Sugar_Cubes macro:

Example of an If...Then statement in Visual Basic for Applications

Let’s take a look at each of the lines in this code snippet:

  • The first line states 2 conditions that can evaluate to either true or false.

    This particular line asks Excel to check whether the value of sugarCubes (the amount of sugar cubes that a particular caretaker has given to the horse) is less than 1 or more than 2. In other words, this is where Excel confirms whether a particular caretaker has complied with the rule that requires him to give 1 or 2 sugar cubes per day to the horse.

    If either of these 2 conditions is true, Excel executes the statement that appears in the second row. If neither of the 2 conditions is true (both are false), Excel doesn’t execute the statement in the second line.

  • The second line tells Excel what it should do if either of the 2 conditions set in the first line is true.

    In this case, if a caretaker has not given any sugar cubes (less than 1) or has given more than 2 sugar cubes to the horse in a particular day, Excel displays a message in a dialog box reminding that caretaker that he “should give 1 or 2 sugar cubes per day to the horse”.

  • The third line terminates the If…Then…Else block.

You now know how to create the variables that store the number of sugar cubes given to the horse by each caretaker and the identification number of each caretaker. You also know how to get Excel to remind a caretaker of the rule that states they should give 1 or 2 sugar cubes per day to the horse in case they haven’t done so.

You only need one extra VBA component to complete the basic structure of you Horse_Sugar_Cubes macro:

How do you get Excel to ask each of the 5 caretakers how many sugar cubes he has given to the horse?

I help you answer this question in the following section.

What Is A Loop?

Loops are statements that:

  • Are specified once, but…
  • Are carried out several times.

In other words, a loop is a particular statement that makes a group of instructions be followed multiple times. Just as conditional statements, there are several ways in which you can structure loops.

However, for purposes of the Horse_Sugar_Cubes application, you can can use a For Each…Next statement. This statement asks Excel to execute a group of statements repeatedly for each of the components of a particular group.

In practice, this looks roughly as follows. This is the For Each…Next statement of the Horse_Sugar_Cubes macro that I am using as example in this Excel VBA tutorial for beginners.

Example of a For Each loop in Visual Basic for Applications

Notice that the conditional statement that I explain in the section above is there.

Example of a condition within a loop in Visual Basic for Applications

However, what is more relevant for purposes of this section is the general structure of a For Each…Next statement, so let’s take a look at it.

  • At the beginning, a For Each…Next statement must say “For Each element of a certain type in the particular group”. In the example above, this line is as follows:

    Example of opening line of a For Each...Next statement in Visual Basic for Applications
    The word element refers to the particular items of a collection through which the loop should run. In the case I am using as an example, the elements are sugarCubes.

    In this particular case, sugarCubes is defined as a Range object variable. If you’re in a situation where the element has not been declared previously, you declare its data type.

    The last portion of the statement refers to the group in which the elements are. In this case, this is the range of cells C5 through C9. This is the collection over which the statements inside the loop is repeated.

    In other words, Excel applies the set of instructions inside the loop to each of the cells highlighted in the following screenshot.

    Example of the elements of a collection used in a VBA loop

  • The body of a simple For Each…Next statement such as the one in the Horse_Sugar_Cubes macro includes a certain number of instructions that Excel applies to each of the elements in the group (according to what has been stated in the first line).

    In the example being used in this Excel VBA tutorial for beginners, the body of statements looks as follows:

    Example of the statements inside a For Each...Next statement in Visual Basic for Applications
    The above group of statements is a very simple example. There are structures that are more complicated than this, involving statements (such as Continue For or Exit For) which can be used to transfer the control to different parts of the VBA code.

  • The last statement of the For Each…Next statement is of the form “Next element”. In the example above, this looks as follows:

    Example of closing line of a For Each...Next statement in Visual Basic for Applications
    This statement simply terminates the definition of the loop and tells Excel that, after carrying out the instructions inside the loop, it should move to the next element (in this case, the next sugarCubes).

To summarize, the opening and closing lines of the For Each…Next statement tell Excel that it should run the instructions that are inside the loop for each of the 5 cells where the number of sugar cubes given to the horse by each caretaker are to be recorded.

Macro Example: Horse_Sugar_Cubes

Before I end this Excel VBA tutorial for beginners, let’s take a final line-by-line look at the complete VBA code behind the Horse_Sugar_Cubes macro to review some of the essential terms that have been covered in this guide and understand each of the instructions behind the application.

Example of VBA code

For ease of reference, here is once more an illustration of how the Horse_Sugar_Cubes macro works in practice:

Example of how a VBA application works when running in Excel

Let’s go through the main items of this macro while making some general comments to further illustrate each of the terms covered in this tutorial:

#1. General aspects.

The Horse_Sugar_Cubes application is written in Visual Basic for Applications or VBA, the programming language you can use to communicate instructions to Excel.

Horse_Sugar_Cubes itself is a macro, a sequence of instructions for Excel to follow. The code that appears in the screenshot above is an example of VBA code. The terms macro, VBA code, Sub procedure, routine and procedure are sometimes used interchangeably.

The VBA code behind the Horse_Sugar_Cubes application is stored by Excel in a module, the container where Excel stores the VBA code.

The Horse_Sugar_Cubes macro has several statements, or instructions.

#2. Sub Horse_Sugar_Cubes() and End Sub.

Example of the declaration of a sub procedure in VBA code

The first line of code in the screenshot above declares the sub procedure Horse_Sugar_Cubes. A Sub procedure is the series of statements that are between the Sub and the End Sub statements and, more precisely, is a part of a computer program that performs an action.

The other main type of procedure in VBA are Function procedures, which carry out calculations and return a particular value.

The last line of code in the screenshot above terminates the execution of the sub procedure Horse_Sugar_Cubes. Once Excel executes this line, the macro stops running.

#3. Dim caretakerNumber As Integer and Dim sugarCubes as Range.

Example of how 2 variables are declared in Visual Basic for Applications

In Visual Basic for Applications, variables are usually declared using the Dim statement. After this, you can determine the name of the variable and its characteristics. The computer allocates a storage location to the variable and, then, you can use the declared variable as a placeholder to represent a particular value.

In the example above, 2 variables are declared. caretakerNumber is declared as an integer and sugarCubes as a range.

#4. caretakerNumber = 1.

Example of how to assign a value to a variable in VBA

This line is an assignment statement which assigns the value 1 to the variable caretakerNumber. As a consequence of this assignment, every time that the Horse_Sugar_Cubes macro is executed, caretakerNumber is set to the initial value of 1.

#5. For Each…Next statement.

Example of a For Each...Next statement in Visual Basic for Applications

A For Each…Next statement asks Excel to execute a group of statements repeatedly for each member of a group. This type of statement is one of the simplest ways to implement a loop, a statement that makes a particular group of instructions be repeated several times.

In the case of the Horse_Sugar_Cubes macro, the loop asks Excel to repeat the relevant set of instructions for each of the 5 caretakers of the horse. Let’s take a look at the body of the For Each…Next statement to understand the set of instructions that is repeated:

  • sugarCubes.Value = InputBox(“Number of sugar cubes given to horse by caretaker ” & caretakerNumber).

    Example of a statement inside a For Each...Next statement in Visual Basic for Applications


    The first part of the line (sugarCubes.Value =) assigns a value to the variable sugarCubes.

    The second part of the statement (InputBox(“Number of sugar cubes given to horse by caretaker ” & caretakerNumber)) instructs Excel to show a pop-up input box that asks what is the number of sugar cubes given to the horse by each caretaker. The number that is inputted in the box is recorded in the relevant cell of the Excel worksheet and is the value assigned to the variable sugarCubes.

    The input box refers to each caretaker by its identification number (1 through 5) by calling the value of the variable caretakerNumber (for example, the first caretaker is referred to as caretaker 1, and so on). As a consequence of the statement immediately above the For Each…Next statement (caretakerNumber = 1), the value of the variable caretakerNumber at the beginning of the process is always 1. I explain further below which statement asks Excel to update the caretaker number for the relevant caretaker.

  • Conditional statement.

    Example of a conditional statement in Visual Basic for Applications
    Conditional statements evaluate a particular condition and, depending on the result (true or false), Excel carries out (or refrains from carrying out) certain actions.

    The conditional statement in the Horse_Sugar_Cubes macro evaluates whether a caretaker has given less than 1 or more than 2 sugar cubes to the horse (therefore not complying with the rule that requires them to give either 1 or 2 sugar cubes per day to the horse). If any of the 2 conditions is met (the number of sugar cubes given to the horse is less than 1 or more than 2), Excel displays a message box with a reminder that states “You should give 1 or 2 sugar cubes per day to the horse”.

  • caretakerNumber = caretakerNumber + 1.This statement increases the value of the variable caretakerNumber by 1 for each successive repetition of the For Each…Next statement.

    Therefore, the second time the set of instructions is repeated by the macro, caretakerNumber is equal to 2. The third time, the variable has the value of 3. As you may expect, the values for the fourth and fifth times are 4 and 5 respectively.

Conclusion

You have made it to the end of this Excel VBA tutorial for beginners.

By now, based on what you have learned on this beginners guide, you know the meanings of at least 16 essential terms you need to know to learn VBA programming. You’re also able to understand how some of these terms are sometimes used interchangeably and some of the discussions regarding their use.

Additionally, you’ve seen how these concepts come together to form a macro, and you know how some of the VBA components that have been explained in this Excel VBA tutorial for beginners can be implemented in practice.

I hope that this Excel tutorial for beginners has proved that the most essential terms you need to know to learn VBA programming are not that complicated to understand.

You’re likely to find the terms that have been covered in this particular guide for beginners many times during your journey to becoming a VBA expert so you may want to bookmark this post and come back as required during your future Visual Basic for Applications studies.

Понравилась статья? Поделить с друзьями:
  • All about excel in selenium
  • All about excel in computer
  • All about excel graphs
  • All about excel functions
  • All about excel forms