Activex objects in excel

Добавление или регистрация элемента ActiveX

​Смотрите также​​ Вопрос в том​.​.​ редакторе Visual Basic​ Для удобства также​. Откройте вкладку​ нарисуйте его с​, подумайте о том,​ вам полезна. Просим​ какой тип элемента​ от 1 до​ формулу =ПОИСКПОЗ($E$9; $G$9:$K$9;0)​правой клавишей вызовите его​ Нужный элемент управления​ опции, делать выбор​ убедитесь, что вы​Примечание:​ как этого избежать?​Выберите категорию​В редакторе Visual Basic​ напишите новый макрос.​

​ приводим ссылку на​Alphabetic​ помощью перетаскивания.​ чтобы использовать элемент​ вас уделить пару​ управления — просто​ 5 (т.е. от​ Если выбран 2009,​ контекстное меню, затем​ выбирается с помощью​ и пр. В​ находитесь в режиме​Мы стараемся как​Спасибо​Популярные​ создайте новый или​Дополнительные сведения о том,​ оригинал (на английском​(По алфавиту) и​Советы:​ ActiveX «Список».​

​ секунд и сообщить,​​ просмотрев его. Определение​

  • ​ 2009 до 2013​ то формула вернет​ Формат объекта…, вкладка​ группы Переключателей. Название​ принципе, без них​ конструктора. На вкладке​ можно оперативнее обеспечивать​Serge_007​, а затем в​ измените имеющийся макрос.​ как создавать макросы,​ языке) .​ измените нужные свойства.​​ ​​Упростите ввод данных для​

  • ​ помогла ли она​ типа элемента управления,​ года) + 6)​ 1.​ Элемент управления;​ выбранного элемента подсвечивается​ можно обойтись, но​

Добавление элемента управления ActiveX

  1. ​Разработчик​​ вас актуальными справочными​​: 1. Параметр «​​ разделе​​Дополнительные сведения о том,​​ обратитесь к справочной​​Элемент управления формы или​Вот как можно настроить​​Чтобы изменить размер поля,​​ пользователей, позволив им​ вам, с помощью​​ который вы работаете,​​ совпадет с номером​Для определения ячейки строки​в поле Формировать список​ серым цветом (см.​

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

  2. ​ они делают управление​в группе​ материалами на вашем​

    • ​Не перемещать и не​Основные параметры работы с​ как создавать макросы,​ системе Visual Basic.​​ элемента управления ActiveX​​ свойства поля со​​ наведите указатель мыши​​ выбирать значение из​​ кнопок внизу страницы.​​ щелкните правой кнопкой​

      Режим конструктора на ленте

    • ​ текущего столбца (7,​ Количество, соответствующую выбранному​​ по диапазону вводим​​A8:B8​​ данными на листе​​элементы управления​​ языке. Эта страница​​ изменять размеры​

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

      ​ Для удобства также​​ мыши элемент управления​​ т.е. 2009 год);​ году используем формулу​ Список (вместо ссылки​на рис. выше).​ более наглядным и​включите​ переведена автоматически, поэтому​» установлен?​установите флажок​ системе Visual Basic.​​    Выполните одно из действий,​​ следующее:​

Регистрация элемента ActiveX

  1. ​ рисунке:​ маркеров изменения размера​ Поле со списком​

  2. ​ приводим ссылку на​ и затем Обратите​Флажок Условное форматирование установлен.​ =СМЕЩ($F$10;0;СмещГода). Формула вернет​​ на ячейку мы​​ Выбранный год выделяется​​ уменьшают вероятность ввода​​Режим конструктора​​ ее текст может​ Изображение кнопки​2. Лист с​

  3. ​Показывать вкладку «Разработчик» на​​Когда макрос будет создан,​​ описанных ниже.​​Выполните действие или операцию,​​Настраиваемое свойство​​ и перетащите границу​​ состоит из текстового​​ оригинал (на английском​​ внимание на следующее:​​выберите требуемый формат, например,​​ диапазон, состоящий из​

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

  4. ​ ввели ссылку на​ в таблице Условным​​ некорректных данных.​​.​​ содержать неточности и​​ кнопками защищён?​

  5. ​ ленте​​ выберите команду​​Правка назначенного макроса​ когда пользователь щелкает​Действие​ элемента управления до​ поля и списка,​ языке) .​

  6. ​Если контекстное меню содержит​ серый цвет заливки;​​ одной ячейки.​​ определенное Имя!). Конечно,​

support.office.com

Элементы управления формы в MS EXCEL

​ форматированием темно серым​Для вставки элементов управления​Чтобы задать свойства элемента​ грамматические ошибки. Для​Если на оба​и нажмите кнопку​Закрыть и вернуться в​    Щелкните имя макроса в​ элемент управления формы​Цвет заливки​ достижения нужной высоты​ которые вместе образуют​Если вам нужно отобразить​ команду​нажмите ОК.​В поле Связь с​

​ вместо имени можно​ цветом (см.​ на лист необходимо​

  • ​ управления на вкладке​ нас важно, чтобы​ вопроса ответ​ОК​ Microsoft Excel​ поле​
  • ​ нужно назначить макрос.​Щелкните свойство​ и ширины.​​ раскрывающийся список.​​ список значений, которые​​Назначить макрос​​убедимся, что флажок Условное​​ ячейкой элемента Полоса​​ было указать просто​​H9:H12​ отобразить вкладку Разработчик.​​Разработчик​​ эта статья была​​ДА​

​.​в меню​Имя макроса​Запустите Microsoft Visual Basic​

​BackColor​Чтобы переместить поле со​Можно добавить поле со​ сможет выбирать пользователь,​, это элемент управления​ форматирование установлен;​ прокрутки нельзя ввести​ ссылку на диапазон;​на рис. выше).​В MS EXCEL 2007​в группе​ вам полезна. Просим​, то:​Примечание:​Файл​и нажмите кнопку​ для приложений (VBA)​(Цвет фона), щелкните​

​ списком на листе,​ списком одного из​ добавьте на лист​ формы.​выберем переключатель Список;​ формулу, но можно,​

  • ​свяжем элемент с ячейкой​
  • ​ Отображение этого выделения​
  • ​ это можно сделать через​
  • ​элементы управления​
  • ​ вас уделить пару​
  • ​1. Для чего​

​ Лента входит в Пользовательский​редактора Visual Basic.​Правка​ позволяет обработать все​ стрелку вниз, откройте​

Пример

​ выделите его и​ двух типов: элемент​ список.​Совет:​в элементе управления Список​ как мы уже​$C$8​ регулируется Флажком (фон​​ меню Кнопка офис/ Параметры​​нажмите кнопку​

​ секунд и сообщить,​ используются кнопки?​ интерфейс Microsoft Office​После завершения разработки элемента​.​ события, возникающие при​ вкладку​ перетащите в нужное​ управления формы или​Создайте перечень элементов, которые​ Чтобы отобразить правильное контекстное​​ выберем 2010;​​ видели, ввести Имя.​. В этой ячейке​ флажка — красный).​ Excel/ Основные/ Показывать​Свойства​​ помогла ли она​​2. Файл расшарен?​ Fluent.​ управления, на вкладке​Назначение другого существующего макроса​ взаимодействии пользователя с​Pallet​ место.​ элемент ActiveX. Если​ должны отображаться в​ меню для группы​

Переключатели

​убедимся, что столбец 2010​ Создадим Именованную формулу Количество,​ будет выводится порядковый​ Полосами прокрутки можно​ вкладку Разработчик на​.​

​ вам, с помощью​ЗЫ Во вложении​Убедитесь в том, что​Разработчик​    Дважды щелкните макрос в​ элементом ActiveX.​(Палитра) и выберите​Щелкните правой кнопкой мыши​ необходимо создать поле​ списке, как показано​ элемент управления формы,​ выделен серым;​​ в поле Диапазон​​ номер выбранного элемента​ редактировать Цену и​ ленте.​Совет:​ кнопок внизу страницы.​

​ файл. Попробуйте как​​ вы находитесь в​​в группе​ списке или введите​Дополнительные сведения о создании​ цвет.​ поле со списком​ со списком, в​ на рисунке.​ убедитесь, что выбран​Полосой прокрутки изменим количество​​ укажем формулу =СМЕЩ($F$10;0;СмещГода).​​ списка, т.е. если​ Количество в выбранном​В MS EXCEL 2010​

Поле со списком

​ Можно также щелкнуть элемент​ Для удобства также​ либо изменить кнопку​ режиме конструктора. На​элементы управления​ его имя в​​ макросов, узнайте, Создание​​Тип, начертание или размер​ и выберите команду​ котором пользователь сможет​На вкладке​ периметр группы, а​ в столбце 2010.​

​ Теперь в поле​

  • ​ выберем 2009, то​​ году, но только​​ это можно сделать так:​
  • ​ управления правой кнопкой​ приводим ссылку на​
  • ​ или её положение​ вкладке​

​отключите​ поле​ или удаление макросов.​

  • ​ шрифта​Формат объекта​
  • ​ изменять текст в​Разработчик​ не ее внутреннюю​Результат показан на рисунке.​
  • ​ Связь с ячейкой​ выведется 1, т.к.​ в определенном диапазоне.​ Откройте вкладку​ мыши и выбрать​ оригинал (на английском​andrey-p​Разработчик​Режим конструктора​
  • ​Имя макроса​​Щелкните элемент управления правой​​Щелкните свойство​.​ текстовом поле, рассмотрите​нажмите кнопку​ часть группы.​К сожалению, у элементов​ элемента полоса прокрутки​ это первый элемент​ Теперь – подробнее.​Файл​ пункт​ языке) .​: Serge_007,​в группе​​.​​.​

Список

​ кнопкой мыши и​Font​Откройте вкладку​ возможность использования элемента​​Вставить​​Если контекстное меню содержит​ управления формы Флажок,​ введите Количество.​ в списке. Для​​На листе использовано 3​​; Нажмите кнопку​

Счётчик

​Свойства​Кроме различных элементов формы​1. Нет​элементы управления​Примечание:​Если вкладка​​ выберите команду​​(Шрифт), нажмите кнопку​Элемент управления​ ActiveX «Поле со​.​

​ команду​ Поле со списком​Аналогичные манипуляции проделайте с​ дальнейших целей нам​ Переключателя объединенных в​Параметры​​.​​ компьютера содержит много​2. Да​включите​​Мы стараемся как​​Разработчик​

Полоса прокрутки

​Назначить макрос​…​и настройте следующие​ списком». Элемент ActiveX​Примечание:​Свойства​ и Список нет​ полосой прокрутки для​ проще использовать именно​ Группу. Каждому Переключателю​; Нажмите кнопку​Появится диалоговое окно​

​ элементы ActiveX, установленные​Файл во вложении​Режим конструктора​ можно оперативнее обеспечивать​​недоступна, отобразите ее.​​.​и выберите тип,​ параметры.​ «Поле со списком»​ Если вкладка​, элемент управления является​ возможности отформатировать отображаемый​ Цены. Для этого​ год, а не​

​ соответствует определенный элемент​Настроить ленту​Свойства​ приложением Excel и​ (пароль 180285). На​.​

​ вас актуальными справочными​В Excel 2016, 2013,​Откроется диалоговое окно​ размер или начертание​Формировать список по диапазону​ более универсален: вы​Разработчик​ элементом ActiveX и​ шрифт. Зато это​ необходимо создать Именованную формулу​ его порядковый номер.​ управления: Поле со​; Выберите команду​

​. Для получения подробных​ других программ, таких​ кнопках разные функции​Выберите элемент управления ActiveX.​ материалами на вашем​ 2010:​Назначить макрос объекту​

Флажок

​ шрифта.​: введите диапазон ячеек,​ можете изменить свойства​​не отображается, на​​ Excel открывается в​ можно сделать у​ Цена, где в​ Для этого в​ списком, Список, Счетчик.​

​Настройка ленты и в​ сведений о том​ как Calendar Control​ (вызов форм, сортировка…).​Дополнительные сведения установите или​ языке. Эта страница​В меню​.​​Цвет шрифта​​ содержащий список элементов.​ шрифта, чтобы текст​ вкладке​ режиме конструктора.​ элементов ActiveX (Разработчик/​ поле Диапазон указать​ ячейку​

​Для объединения Элементов в​ разделе Основные вкладки​​ или ином свойстве​​ 12.0 и проигрыватель​Файл всегда защищен,​ снимите флажок элементы​ переведена автоматически, поэтому​Файл​Чтобы задать местонахождение существующего​Щелкните свойство​Связь с ячейкой​ было легче читать​Файл​Если контекстное меню содержит​ Элементы управления/ Вставить).​ формулу =СМЕЩ($F$11;0;СмещГода).​D8​ группу помещаем на​​установите флажок​​ выделите его и​

  • ​ Windows Media. При​ но вопрос в​ управления на листесм.​
  • ​ ее текст может​последовательно выберите пункты​
  • ​ макроса, выберите его​ForeColor​: поле со списком​ на листе с​выберите​ команду​ Правда, для работы​
  • ​При выборе пользователем текущего​введем формулу =C8+2008.​ лист Элемент управления​Разработчик​ нажмите клавишу F1,​ установке новых элементов​ том что каким-то​Щелкните правой кнопкой мыши​
  • ​ содержать неточности и​
  • ​Параметры​ в списке​
  • ​(Цвет текста), щелкните​

Тестируем

  • ​ можно связать с​ измененным масштабом. Кроме​
  • ​Параметры​
  • ​Назначить макрос​ с этими элементами​
  • ​ года, в таблице​Вставляем на лист элемент​
  • ​ Группа (через меню​.​

​ чтобы отобразить соответствующий​

​ управления ActiveX, программа​ образом в результате​ выделенного фрагмента.​ грамматические ошибки. Для​и​Находится в​ стрелку вниз, откройте​ ячейкой, где отображается​ того, такое поле​>​, используется объект средства​ требуется писать программу​ с данными (​

excel2.ru

Почему не удается выделить элементы управления формы и элементы ActiveX?

​ Список. Аналогично предыдущему​​ Разработчик/ Элементы управления/​Теперь вставить элемент управления​ раздел справка по​ установки для элементов​ неизвестных мне процессов​Выберите имя объекта (например,​ нас важно, чтобы​Настроить ленту​, выполнив одно из​ вкладку​ номер элемента при​ со списком можно​Настроить ленту​ рисования.​ на VBA.​G9:K12​ элементу связываем его​ Вставить). В рамках​ можно через меню:​ Visual Basic. Можно​

Признаки

​ обычно регистрирует каждый​ неоднократно сталкивался с​

Причина

​Объект флажок​

  • ​ эта статья была​.​ указанных ниже действий.​Pallet​ его выборе из​ программно разместить в​. В списке​Затем выполните следующее:​Примечание:​) соответствующий столбец будет​ с ячейкой​

  • ​ группы создаем 3​ Разработчик/ Элементы управления/​ также ввести имя​ из элементов управления​ тем, что кнопки​) и нажмите​ вам полезна. Просим​В разделе​

  • ​Для поиска макроса во​(Палитра) и выберите​ списка. Введите номер​

Разрешение

​ ячейках, содержащих список​Основные вкладки​В элементе управления формы​ Мы стараемся как можно​ закрашиваться серым фоном.​$C$13​ переключателя (также через​ Вставить.​ свойства в поле​ на вашем компьютере,​ меняются автоматически, причем​ кнопку​ вас уделить пару​Настройка ленты​ всех открытых книгах​ цвет.​ ячейки, где должен​

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

    ​и формируем список​​ меню Разработчик/ Элементы​Обратите внимание, что в​Поиск​ который делает его​ пользователь этого сделать​Изменить​ секунд и сообщить,​

  • ​установите флажок​ выберите значение​​Связь с ячейкой для​​ отображаться номер элемента.​Выберите столбец, который можно​ вкладки​ и убедитесь, что​

  • ​ актуальными справочными материалами​ выбранного года используем​​ на основе того​​ управления/ Вставить) и​ этом меню можно​

​справки Visual Basic.​

  • ​ доступным для использования​ никак не может​.​ помогла ли она​Разработчик​

    Границу элемента управления

  • ​Все открытые книги​

    1. ​ отображения значения, выбранного​​Например, в ячейке C1​​ скрыть на листе,​

      1. ​Разработчик​​ отображается границу элемента​​ на вашем языке.​​ Условное форматирование.​​ же Именованного диапазона​

      2. ​ связываем их все​​ вставить Элементы ActiveX,​​Щелкните элемент управления ActiveX,​​ из Excel. Если​​ и не понятно​

      3. ​Редактирование текста в элементе​​ вам, с помощью​​и нажмите кнопку​

    2. ​.​ в списке​ отображается значение 3, если​ и создайте список,​​и нажмите кнопку​​ управления.​​ Эта страница переведена​​Сначала вставим на лист​​ Список. В ячейку​​ с одной ячейкой​

      Режим конструктора

  • ​ которые расположены ниже​ который вы хотите​ элемент управления не​ в какой момент​ управления.​ кнопок внизу страницы.​

    ​ОК​Примечание:​Щелкните свойство​

support.office.com

Добавление списка или поля со списком на лист в Excel

​ выбрать пункт​​ введя по одному​ОК​Для элемента управления ActiveX:​ автоматически, поэтому ее​ элемент Флажок. Этим​D13​С2​ интересующих нас Элементов​ зарегистрировать.​ отображается в списке,​ меняются.​После завершения редактирования текста,​ Для удобства также​.​ Если макрос, который нужно​LinkedCell​Фруктовое мороженое​ значению в ячейки.​.​Если вкладка​ текст может содержать​

​ элементом мы будем​введем формулу =C13+2008.​(выделив элемент управления,​ управления формы. У​Убедитесь в том, что​

Образец списка

Добавление списка на лист

  1. ​ необходимо зарегистрировать его​Спасибо за ответ,​ нажмите клавишу ESC.​ приводим ссылку на​

    список значений для использования в поле со списком

  2. ​В Excel 2007​​ назначить элементу управления,​​(Связанная ячейка).​​, так как это​​Примечание:​

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

  3. ​недоступна, отобразите ее:​​ ошибки. Для нас​​ выделение в таблице​​ Счетчик. Определяем минимальное​​ контекстное меню, Формат​

    кнопка управления формой списка

  4. ​ одни и те​ режиме конструктора. На​

  5. ​Важно:​​ свойства, попробую, думаю​​Веб-браузеры отображают альтернативный (замещающий​​ языке) .​​кнопку Microsoft Office​

    Свойства элемента управления списком.

    • ​ книге, чтобы он​​ и списка элементов​​ списке.​ на другом листе​

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

    • ​ объекта…, вкладка Элемент​​ же элементы Кнопка,​​ вкладке​ ​

      ​ поможет.​​ текст) во время​Вы можете изменить текст,​, а затем —​ появился в списке​Щелкните поле рядом со​Совет:​ той же книги.​

    • ​Список (элемент управления формы)​​Файл​​ статья была вам​​ Элемент свяжите с​​ – 2013, шаг​​ управления).​​ Список, Флажок и​

      ​Разработчик​​Не все элементы управления​Serge_007​​ загрузки изображений, если​​ отображаемый в элементе​​ кнопку​​Находится в​ свойством​  Чтобы вместо номера​

Добавление поля со списком на лист

​На вкладке​.​и выберите пункт​ полезна. Просим вас​ ячейкой​ 1. Связываем элемент​Удерживая клавишу​ т.п.  Разница между​в группе​

Поле со списком

​ ActiveX можно использовать​: Поможет. Вы мой​ отсутствуют изображения, а​ управления формы или​Параметры Excel​, сначала откройте книгу,​ListFillRange​ отображать сам элемент,​Разработчик​Щелкните ячейку, в которой​Параметры​ уделить пару секунд​$G$2​ с ячейкой​CTRL​ ними следующая: чтобы​элементы управления​ непосредственно на листах;​ файл смотрели? Пробовали​ также отображают замещающий​ элемента управления ActiveX,​.​ содержащую макрос.​(Диапазон элементов списка)​ можно воспользоваться функцией​

  1. ​нажмите кнопку​ нужно создать список.​.​ и сообщить, помогла​. Если флажок снят,​

    список значений для использования в поле со списком

    ​$C$17D17​​выделяем 3 переключателя​ использовать Элементы ActiveX необходимо​включите​

  2. ​ некоторые могут быть​​ что либо сделать​​ текст, если навести​​ например метки или​​В категории​

    ​Чтобы ограничиться при поиске​​ и укажите диапазон​​ ИНДЕКС. В нашем​​Вставить​Нажмите кнопку​​В раскрывающемся списке​​ ли она вам,​​ то в этой​​введем формулу =С17,​​ и элемент Группа,​​ использовать VBA, а​​Режим конструктора​​ использованы только на​ с кнопкой?​​ указатель мыши на​​ справочных сведений, и​​Основные​​ макросов только книгой,​

  3. ​ ячеек для списка.​ примере поле со​.​

    • ​Свойства​​настроить ленту​​ с помощью кнопок​​ ячейке будет ЛОЖЬ​ т.к. элемент Счетчик​​ вызываем правой клавишей​

      ​ Элементы управления формы​

    • ​.​​ Microsoft Visual Basic​​Quote​​ изображение. Поисковые используют​ можно изменить описание​​в разделе​

      Добавление поля со списком

  4. ​ содержащей текущий лист,​Изменение количества отображаемых элементов​ списком связано с​Примечание:​и на вкладке​

​выберите​​ внизу страницы. Для​

  • ​ (этому значению соответствует​ в нашем случае​ мыши контекстное меню​ можно напрямую привязать​На вкладке​ для приложений (VBA)​(andrey-p)200?’200px’:»+(this.scrollHeight+5)+’px’);»>кнопки меняются автоматически​ замещающий текст для​

  • ​ замещающего текста для​Основные параметры работы с​ выберите пункт​ списка​ ячейкой B1, а​

Форматирование элемента управления формы «Поле со списком»

  1. ​ Если вкладка​Элемент управления​Основные вкладки​​ удобства также приводим​​ 0), если установлен,​

  2. ​ возвращает значение года.​​ и выбираем Группировка/​​ к ячейке на​Разработчик​

    Диалоговое окно

    • ​ пользовательские формы. При​​Ну, чудес-то не​ поиска веб-страниц. Замещающий​

    • ​ элемента управления.​​ Excel​Эта книга​Щелкните поле​ диапазон ячеек для​Разработчик​задайте необходимые свойства:​.​ ссылку на оригинал​

      ​ то ИСТИНА (этому​Чтобы определить значение какого​ Группировать. Теперь при​​ листе.​​в группе​ работе с этими​ бывает​

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

      ​ текст также используется​​Редактирование текста в элемент​установите флажок​.​ListRows​ списка — A1:A2. Если​не отображается, на​В поле​Установите флажок​ (на английском языке).​ значению соответствует 1).​ элемента (поле со​​ выборе одного из​​Для тех, кто не​элементы управления​ элементами управления при​Всегда есть причина​

      Введите формулу, чтобы отобразить элемент из связанной ячейки

    • ​ для пользователей с​​ управления формы​Показывать вкладку «Разработчик» на​Чтобы ограничиться при поиске​и введите число​ в ячейку C1​ вкладке​Формировать список по диапазону​Разработчик​Выбор элемента управления, бывает​Для настройки Условного форматирования выделим​ списком, список или​ трех Переключателей в​ ранее не работал​

      Отображается полоса прокрутки.

  3. ​нажмите кнопку​​ попытке добавить их​​andrey-p​

Форматирование элемента ActiveX «Поле со списком»

  1. ​ ограниченными возможностями.​​Редактирование текста в элементе​​ ленте​​ макросов только конкретной​​ элементов.​

  2. ​ ввести формулу​Файл​введите диапазон ячеек,​​.​​ сложно и непредсказуемые.​​ диапазон​​ счетчик) является активным​ Группе, в ячейке​

    ​ с Элементами управления​Вставить​ на лист Excel​: Serge_007,​

    Пример поля со списком.

    Параметры свойств для элемента ActiveX

    ​Выделите элемент управления.​

    ​ управления ActiveX​

    ​, а затем нажмите​

    ​ книгой, выберите среди​​Закройте область​​=ИНДЕКС(A1:A5;B1)​выберите​ содержащий список значений.​​Убедитесь в том, что​​Может быть несколько причин:​G9:K12​

    Свойство цветной заливки для поля со списком.

    ​ в настоящий момент,​С2​

    ​ формы, советуем подробно​​и в группе​​ отображает сообщение​​Ваш файл пробовал,​​Дополнительные сведения установите или​Изменить описание замещающего текста​ кнопку​

    Параметры шрифтов в текстовом поле

    ​ имен доступных открытых​

    ​Properties​​, то при выборе​​Параметры​Примечание:​ Excel открывается в​​Поскольку элемент управления формы​​. Так как формула​ в ячейке​

    ​будет выводиться значение​ ознакомиться с ними​Элементы управления ActiveX​

    ​не удается вставить объект​​ кнопка не меняется.​​ снимите флажок элементы​

    ​ для элемента управления​ОК​

    ​ книг нужную книгу.​(Свойства) и нажмите​​ третьего пункта в​​>​ Если нужно отобразить в​ режиме конструктора. На​

    ​ может содержать текст​ в Условном форматировании​

    ​E9​​ 1, 2 или​​ в следующих статьях:​, нажмите кнопку​

  3. ​.​​ В моем файле​​ управления на листесм.​Выделите элемент управления формы.​​.​​Выполните одно из действий,​

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

support.office.com

Добавление и изменение макроса для элемента управления на листе

​введем формулу: =ЕСЛИ(C2=1;D8;ЕСЛИ(C2=2;D13;D17))​​ 3.​Флажок;​Другие элементы​Вам необходимо включить вкладку​ кнопка тоже не​Правой кнопкой мыши, выберите​Дополнительные сведения установите или​Чтобы изменить элемент ActiveX,​ описанных ниже.​Режим конструктора​ текст «Фруктовое мороженое».​. В списке​ можно изменить размер​Разработчик​ (например, изображение), при​ ссылку, то убедимся,​ Как мы помним,​Теперь вставим элемент управления​Счетчик;​.​ «Разработчик» на ленте,​

​ меняется, так как​ пункт​ снимите флажок элементы​ убедитесь, что вы​

  • ​Назначение макроса​.​Количество строк списка:​Основные вкладки​

  • ​ шрифта для текста.​в группе​ попытке выберите элемент​ что после выделения​ значение в ячейке​ Поле со списком.​

​Полоса прокрутки;​В нижней части диалогового​ прежде чем можно​

Добавление и изменение макроса для элемента управления формы

  1. ​ она под защитой.​Формат элемента управления​ управления на листесм.​​ находитесь в режиме​​    Выполните одно из действий,​

    ​Завершив форматирование, можно щелкнуть​​количество строк, которые​​установите флажок для​

  2. ​В поле​элементы управления​ управления вы могут​​ диапазона активной ячейкой​​С2​ Вставить элемент можно​

    • ​Переключатель;​ окна​ будет работать с​​ Пользователь может ее​​и перейдите на​

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

    • ​ является G9 (т.е.​определяется Группой переключателей.​ через меню: Разработчик/​Список;​​Другие элементы​​ элементами управления ActiveX.​

    • ​ только нажать. Тем​ вкладку​ выберите команду​Разработчик​Запись макроса​

  3. ​ столбец, который содержит​ щелкнуть стрелку вниз.​

    ​Разработчик​​введите ссылку на​Режим конструктора​

    • ​ управления, если выделен​​ диапазон надо выделять​​Вставляем на лист элемент​​ Элементы управления/ Вставить.​Поле со списком.​нажмите кнопку​​ Подробнее читайте вкладку​​ не менее периодически​​Web​​Изменить текст​​в группе​ Изображение кнопки​    Щелкните​

    • ​ список, и выбрать​​ Например, если список​и нажмите кнопку​ ячейку.​.​​ не навести указатель​​ начиная именно с​

    • ​ Полоса прокрутки. Этим​​ В ячейках столбца​​В этой статье рассмотрим​​Зарегистрировать настраиваемый​ «Разработчик».​ ко мне приход​

      ​.​.​элементы управления​запись​

      ​ команду​​ содержит 10 элементов и​ОК​

    • ​Совет:​​При работе с большое​ мыши точно на​​ нее. Подсказкой служит​​ элементом мы будем​​М​​ более сложный пример​

    • ​.​​На вкладке​ пользователи с проблемой,​В поле​Границу элемента управления фильтрацией​​включите​​, а по завершении​

Добавление и изменение макроса для элемента ActiveX

  1. ​Скрыть​​ вы не хотите​​.​

    ​ Выбираемая ячейка содержит число,​ количество элементов управления,​

    1. ​ границу элемента управления.​​ поле Имя, находящееся​​ изменять ячейку на​​введем несколько значений​​ совместного использования элементов​​В диалоговом окне​​Разработчик​

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

    ​Выберите тип поля со​

    1. ​ связанное с элементом,​​ расположенные рядом друг​ Изображение кнопки Office​Если Excel не в​ слева от Строки​​ пересечении строки Количество​​ лет: 2009, 2010,​

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

  2. ​ с другом, увеличить​ режиме конструктора, при​ формул. После выделения​ (строка 10) и​​ 2011, 2012, 2013.​​ форматирования.​​найдите папку, в​​элементы управления​​ кнопки​ Изображение кнопки​ который вы хотите​

  3. ​Редактирование текста в элементе​

    ​Выделите нужный объект.​Разработчик​Мы стараемся как​

  4. ​ введите 10. Если​​ добавить:​​ Его можно использовать​​ большего размера, чтобы​​ попытке выберите элемент​​ диапазона оно должно​ Изображение кнопки​ столбца выбранного года.​

    ​ Эти значения будут​​Разберем конкретный пример применения​ которой находится файл​нажмите кнопку​ABC​​ отобразить.​​ управления.​

  5. ​Дополнительные сведения установите или​в группе​ можно оперативнее обеспечивать​

    ​ ввести число, которое​в разделе​ в формуле для​ увеличить изображение.​

  6. ​ управления ActiveX, вы​ содержать​​ Значения ячейки будет​ использованы в элементе​​ сразу нескольких Элементов​​ элемента управления (с​​Вставить​

  7. ​: например: при активации​andrey-p​​По окончании редактирования текст​​ снимите флажок элементы​​код​​ вас актуальными справочными​​ меньше количества элементов​ Изображение кнопки​Элементы управления формы​

support.office.com

Редактирование текста в элементе управления на листе

​ получения фактического элемента​​Дополнительные сведения читайте в​ можете случайно начать​G9​ меняться в диапазоне​ Поле со списком.​ управления. В файле​ расширением OCX) или​и затем в​ листа — не​: Добрый день.​ правой кнопкой мыши​ управления на листесм.​нажмите кнопку​ материалами на вашем​ в списке, появится​выберите элемент управления​ из входного диапазона.​ статье масштабирование документа,​ действие, например выполнение​).​ от 0 до​

​Создадим Именованный диапазон Список.​ примера с помощью​ DLL-файл элемента управления,​ группе​ пробовали?​Подскажите, пожалуйста, возможно​ и выберите команду​на вкладке​Остановить запись​

В этой статье

​ языке. Эта страница​ полоса прокрутки.​

​Поле со списком (элемент​В группе​

​ презентации или листа.​ макроса или установка​

Редактирование текста в элемент управления формы

  1. ​вызовите инструмент Условное форматирование (Главная/​

    ​ 1000. Но как​выделяем диапазон​ элементов управления показано​

  2. ​ который необходимо зарегистрировать.​Элементы ActiveX​​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Private Sub Worksheet_Activate()​​ кто-нибудь сталкивался с​

    ​Завершить изменение текста​Разработчик​.​

    Текстовое поле с границей со штриховкой

  3. ​ переведена автоматически, поэтому​Нажмите кнопку​

  4. ​ управления формы)​Возможен выбор​Примечание:​​ флажка.​​ Стили/ Условное форматирование/​

​ определить эту ячейку?​

Редактирование текста в элементе управления ActiveX

  1. ​М9:М12​​ как пользователь может​​Выберите файл элемента управления​

    ​выберите элемент управления​

    1. ​CommandButton1.Left = Cells(2,​​ подобной проблемой: на​ Изображение кнопки Office​.​в группе​​Назначение существующего макроса​​ ее текст может​

    2. ​ОК​​;​​установите переключатель​Мы стараемся как​​Многие элементы управления расположены​ Создать правило);​​Создадим Именованную формулу СмещГода​​;​ отредактировать значения в​​ и нажмите кнопку​​ или нажмите кнопку​​ 2).Left ‘Левое​

      ​ листе Excel размещены​​К началу страницы​элементы управления​    Дважды щелкните макрос в​

  2. ​ содержать неточности и​.​ИЛИ:​одинарного значения​​ можно оперативнее обеспечивать​​ рядом друг с​​выберите Использовать формулу для​​ для определения позиции​​нажимаем Формулы/ Определенные имена/​ Изображение кнопки​ таблице (диапазон​

  3. ​Открыть​

    ​Другие элементы управления​CommandButton1.Top = Cells(2,​ кнопки (элемент Activex).​

  4. ​Если вкладка​нажмите кнопку​

  5. ​ списке или введите​​ грамматические ошибки. Для​​На вкладке​в разделе​​и нажмите кнопку​​ вас актуальными справочными​

  6. ​ другом.​ определения форматируемых ячеек;​

  7. ​ выбранного года в​ Присвоить имя;​

​F9:K12​

Изменить описание замещающего текста для элемента управления

​.​, чтобы просмотреть все​ 2).Top ‘верхнее​ С файлом работает​Разработчик​Просмотреть код​ его имя в​ нас важно, чтобы​Разработчик​Элементы ActiveX​ОК​ материалами на вашем​Во-первых определяют тип элемента​

  1. ​в поле «Форматировать значения,​

    ​ диапазоне лет​в поле Имя вводим​).​

  2. ​Элементы управления формы (Поле​ доступные элементы управления​​CommandButton1.Height = Cells(2,​​ много пользователей, в​недоступна, отобразите ее.​​.​​ поле​

  3. ​ эта статья была​​нажмите кнопку​​выберите элемент управления​.​ языке. Эта страница​

support.office.com

Изменяются элементы ActiveX

​ управления, который требуется​​ для которых следующая​
​G9:K9​ Список.​С помощью одного из​ со списком, Флажок,​ ActiveX и выберите​ 2).Height + 10​ какой-то момент (не​Отображение вкладки Разработчик​Примечание:​Имя макроса​ вам полезна. Просим​Режим конструктора​Поле со списком (элемент​Примечание:​ переведена автоматически, поэтому​
​ выделить. Существует три​

​ формула является истинной»​​. Нажимаем Формулы/ Определенные​​Теперь свяжем элемент управления​ 3-х элементов управления​​ Счетчик и др.)​
​ элемент управления.​ ‘высота​
​ понятно какой) происходит​Нажмите​​ Чтобы изменить существующий макрос,​​.​
​ вас уделить пару​.​
​ ActiveX)​
​  Если вы хотите​ ее текст может​ различных типа элементов​ введите =И(СТОЛБЕЦ(G9)=СмещГода+6;$G$2) Формула​

​ имена/ Присвоить имя,​​ с данными на​
​ Поле со списком,​
​ помогают быстро менять​
​Щелкните на листе место,​CommandButton1.Width = Cells(2,​ изменение размера и​кнопку Microsoft Office​
​ щелкните элемент управления​Создание макроса​ секунд и сообщить,​Щелкните правой кнопкой мыши​.​ выбрать параметр​ содержать неточности и​ управления и объекты,​ примет значение ИСТИНА,​ в поле Имя​ листе. Для этого:​ Список и Счетчик,​ данные на листе​
​ где должен отображаться​ 2).Width + 60​ размещения кнопок (порой​, а затем —​

​ правой кнопкой мыши​​    Нажмите кнопку​ помогла ли она​ поле со списком​Щелкните ячейку, в которую​
​набора значений​​ грамматические ошибки. Для​
​ которые можно изменять​ когда выполнится одновременно​smile
​ вводим СмещГода, в​

​выделите элемент управления Поле​​ пользователь может выбрать​
​ в определенном диапазоне,​ элемент управления ActiveX.​ ‘ширина​ их даже трудно​ кнопку​ и выберите команду​Создать​ вам, с помощью​ и выберите пункт​ нужно добавить поле​или​ нас важно, чтобы​ однозначно, вы может​ 2 условия:​

​ поле диапазон вводим​​ со списком;​ столбец таблицы (год).​ включать и выключать​
​Чтобы изменить элемент управления,​
​End Sub​ найти на листе).​
​Параметры Excel​Просмотреть код​
​, а затем в​ кнопок внизу страницы.​Свойства​
​ со списком, и​списка значений​ эта статья была​
​ не наверняка знаете,​

excelworld.ru

​значение выражения (СмещГода (изменяется​

Содержание

  1. Using ActiveX Controls on Sheets
  2. Adding Controls with Visual Basic
  3. Using Control Properties with Visual Basic
  4. Using Control Names with the Shapes and OLEObjects Collections
  5. Support and feedback
  6. Microsoft Excel
  7. Режим конструктора и элементы ActiveX в VBA Excel
  8. Using ActiveX Controls on Sheets
  9. Добавление элементов управления с помощью Visual Basic
  10. Использование свойств элемента управления с Visual Basic
  11. Использование имен элементов управления с коллекциями shapes и OLEObjects
  12. Поддержка и обратная связь

Using ActiveX Controls on Sheets

This topic covers specific information about using ActiveX controls on worksheets and chart sheets. For general information on adding and working with controls, see Using ActiveX Controls on a Document and Creating a Custom Dialog Box.

Keep the following points in mind when you are working with controls on sheets:

In addition to the standard properties available for ActiveX controls, the following properties can be used with ActiveX controls in Microsoft Excel: BottomRightCell, LinkedCell, ListFillRange, Placement, PrintObject, TopLeftCell, and ZOrder.

These properties can be set and returned using the ActiveX control name. The following example scrolls the workbook window so CommandButton1 is in the upper-left corner.

Some Microsoft Excel Visual Basic methods and properties are disabled when an ActiveX control is activated. For example, the Sort method cannot be used when a control is active, so the following code fails in a button click event procedure (because the control is still active after the user clicks it).

You can work around this problem by activating some other element on the sheet before you use the property or method that failed. For example, the following code sorts the range:

Controls on a Microsoft Excel workbook embedded in a document in another application will not work if the user double-clicks the workbook to edit it. The controls will work if the user right-clicks the workbook and selects the Open command from the shortcut menu.

When a Microsoft Excel workbook is saved using the Microsoft Excel 5.0/95 Workbook file format, ActiveX control information is lost.

The Me keyword in an event procedure for an ActiveX control on a sheet refers to the sheet, not to the control.

Adding Controls with Visual Basic

In Microsoft Excel, ActiveX controls are represented by OLEObject objects in the OLEObjects collection (all OLEObject objects are also in the Shapes collection). To programmatically add an ActiveX control to a sheet, use the Add method of the OLEObjects collection. The following example adds a command button to worksheet 1.

Using Control Properties with Visual Basic

Most often, your Visual Basic code will refer to ActiveX controls by name. The following example changes the caption on the control named «CommandButton1.»

Note that when you use a control name outside the class module for the sheet containing the control, you must qualify the control name with the sheet name.

To change the control name you use in Visual Basic code, select the control and set the (Name) property in the Properties window.

Because ActiveX controls are also represented by OLEObject objects in the OLEObjects collection, you can set control properties using the objects in the collection. The following example sets the left position of the control named «CommandButton1.»

Control properties that are not shown as properties of the OLEObject object can be set by returning the actual control object using the Object property. The following example sets the caption for CommandButton1.

Because all OLE objects are also members of the Shapes collection, you can use the collection to set properties for several controls. The following example aligns the left edge of all controls on worksheet 1.

Using Control Names with the Shapes and OLEObjects Collections

An ActiveX control on a sheet has two names: the name of the shape that contains the control, which you can see in the Name box when you view the sheet, and the code name for the control, which you can see in the cell to the right of (Name) in the Properties window. When you first add a control to a sheet, the shape name and code name match. However, if you change either the shape name or code name, the other is not automatically changed to match.

You use the code name of a control in the names of its event procedures. However, when you return a control from the Shapes or OLEObjects collection for a sheet, you must use the shape name, not the code name, to refer to the control by name. For example, assume that you add a check box to a sheet and that both the default shape name and the default code name are CheckBox1. If you then change the control code name by typing chkFinished next to (Name) in the Properties window, you must use chkFinished in event procedure names, but you still have to use CheckBox1 to return the control from the Shapes or OLEObject collection, as shown in the following example.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Microsoft Excel

трюки • приёмы • решения

Режим конструктора и элементы ActiveX в VBA Excel

В наших статьях мы подробно рассмотрим практические примеры, связанные с использованием программирования, которое заложено в Microsoft Office. Оно основывается на языке VBA, название которого в полном виде выглядит так Visual Basic for Application. Учитывая, что все рассматриваемые разработки будут использовать VBA, наша первоочередная задача познакомиться сданным языком.

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

Рис. 1.4. Закладка Основные окна Параметры Excel

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

И в качестве первого шага необходимо в окне, показанном на рис. 1.2, щелкнуть кнопкой Параметры Excel. В результате перед вами откроется новое окно с набором закладок. Здесь на закладке Основные следует сделать установку для отображения на ленте вкладки Разработчик, что реализуется с помощью флажка Показывать вкладку «Разработчик» на ленте (рис. 1.4).

В Microsoft Excel элементы ActiveX можно размещать и на пользовательских формах, и на самих рабочих листах (на верхнем графическом слое, где располагаются рисунки, диаграммы и другие объекты). Часто вставка нескольких элементов ActiveX значительно упрощает работу с данными на рабочем листе. Все элементы управления делятся на две группы: элементы управления формами и элементы управления ActiveX. Оба набора элементов управления имеют свои преимущества и недостатки. В общем случае элементы управления формами проще в применении, но зато элементы ActiveX являются более гибкими. В наших примерах мы будем использовать исключительно элементы ActiveX.

В результате окно приложения Microsoft Excel дополнится новыми пиктограммами, которые нам потребуются в дальнейшем (рис. 1.5). Среди тех, которыми мы будем активно пользоваться на протяжении всей книги, отметим пиктограмму с надписью Вставить. С се помощью на рабочем листе можно размещать элементы ActiveX, которые существенно дополняют функциональность книг Microsoft Excel. Они типичны для различных приложений Windows (речь идет о кнопках, полосах прокрутки, текстовых окнах, переключателях, списках и т. д.). Кроме пиктограммы Вставить мы будем активно пользоваться и другими присутствующими на ленте Режим конструктора, Свойства, Visual Basic и Макросы.

Перед тем как начать какие-либо действия с тем или иным элементом ActiveX, его необходимо поместить на рабочий лист. Это легко выполнить, если воспользоваться пиктограммой Вставить. На рис. 1.6 показано размещение на рабочем листе элемента ActiveX Кнопка.

Рис. 1.5. Отображение вкладки Разработчик на ленте

При наведении курсора мыши на пиктограмму элемента ActiveX Кнопка в качестве подсказки появляется еще один вариант его названия: элемент управления «Кнопка». Далее по тексту мы будем использовать оба варианта названия — элементы ActiveX и элементы управления.

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

Рис. 1.6. Размещение кнопки на рабочем листе в режиме конструктора

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

Появление маркеров (см. рис. 1.6), окружающих элемент ActiveX, как раз и является признаком того, что мы работаем в режиме конструктора (кнопка Режим конструктора в этом случае выглядит нажатой). На начальном этапе создания разработки работа в режиме конструктора сводится к размещению элементов управления на рабочем листе и изменению их свойств. Далее производится программирование различных событий, связанных с элементами управления, листами и книгой в целом.

Важно отметить, что после размещения элемента ActiveX на рабочем листе, в нашей книге (можно даже сказать — на данном листе книги) появился новый элемент, который фактически представляет собой «программный» объект. Аналогичным образом на рабочих листах книг Excel можно размещать и другие элементы ActiveX.

Рис. 1.7. Вид рабочего листа при выходе из режима конструктора

Другой режим можно назвать режимом выполнения или режимом работы (какого-то однозначно принятого названия не существует). Чтобы перейти в этот режим (то есть выйти из режима конструктора), необходимо отжать кнопку Режим конструктора (рис. 1.7). После этого в нашем случае можно просто пощелкать кнопкой, которую мы создали на рабочем листе (функциональные действия, которые можно обеспечить в этом случае, мы рассмотрим в дальнейшем). Далее опять вернемся в режим конструктора. С помощью маркеров, окружающих кнопку, можно легко изменить се размеры. Также с помощью мыши можно перемещать созданную кнопку по рабочему листу.

Источник

Using ActiveX Controls on Sheets

В этом разделе рассматриваются конкретные сведения об использовании элементов ActiveX на листах и листах диаграмм. Общие сведения о добавлении элементов управления и работе с ними см. в разделах Использование элементов ActiveX в документе и Создание настраиваемого диалогового окна.

При работе с элементами управления на листах учитывайте следующие моменты:

Помимо стандартных свойств, доступных для элементов ActiveX, с элементами ActiveX в Microsoft Excel можно использовать следующие свойства: BottomRightCell, LinkedCell, ListFillRange, Placement, PrintObject, TopLeftCell и ZOrder.

Эти свойства можно задать и вернуть с помощью имени элемента activeX. В следующем примере окно книги прокручивается, поэтому CommandButton1 находится в левом верхнем углу.

Некоторые методы и свойства Microsoft Excel Visual Basic отключаются при активации элемента ActiveX. Например, метод Sort нельзя использовать, когда элемент управления активен, поэтому следующий код завершается ошибкой в процедуре события нажатия кнопки (так как элемент управления по-прежнему активен после его щелчка пользователем).

Эту проблему можно обойти, активировав другой элемент на листе перед использованием свойства или метода, который завершился ошибкой. Например, следующий код сортирует диапазон:

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

При сохранении книги Microsoft Excel в формате файла книги Microsoft Excel 5.0/95 сведения об элементе управления ActiveX теряются.

Ключевое слово Me в процедуре события для элемента ActiveX на листе ссылается на лист, а не на элемент управления .

Добавление элементов управления с помощью Visual Basic

В Microsoft Excel элементы activeX представлены объектами OLEObject в коллекции OLEObjects (все объекты OLEObject также находятся в коллекции Shapes ). Чтобы программно добавить элемент ActiveX на лист, используйте метод Add коллекции OLEObjects . В следующем примере на лист 1 добавляется кнопка команды.

Использование свойств элемента управления с Visual Basic

Чаще всего код Visual Basic будет ссылаться на элементы ActiveX по имени. В следующем примере изменяется заголовок элемента управления с именем CommandButton1.

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

Чтобы изменить имя элемента управления, используемое в коде Visual Basic, выберите элемент управления и задайте свойство (Name) в окно свойств.

Так как элементы ActiveX также представлены объектами OLEObject в коллекции OLEObjects , можно задать свойства элемента управления с помощью объектов в коллекции. В следующем примере задается левое положение элемента управления с именем CommandButton1.

Свойства элемента управления, которые не отображаются как свойства объекта OLEObject , можно задать, возвращая фактический объект управления с помощью свойства Object . В следующем примере задается заголовок для CommandButton1.

Так как все объекты OLE также являются членами коллекции Shapes , можно использовать коллекцию для задания свойств для нескольких элементов управления. В следующем примере левая граница всех элементов управления выравнивается на листе 1.

Использование имен элементов управления с коллекциями shapes и OLEObjects

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

Имя кода элемента управления используется в именах его процедур событий. Однако при возврате элемента управления из коллекции Shapes или OLEObjects для листа необходимо использовать имя фигуры, а не код, чтобы ссылаться на элемент управления по имени. Например, предположим, что вы добавили флажок на лист и что имя фигуры по умолчанию и код по умолчанию — CheckBox1. Если затем изменить имя кода элемента управления, введя chkFinished рядом с (Name) в окно свойств, необходимо использовать chkFinished в именах процедур событий, но вам все равно придется использовать CheckBox1 для возврата элемента управления из коллекции Shapes или OLEObject, как показано в следующем примере.

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

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

Источник

Excel VBA — ActiveX Controls, Form Controls & AutoShapes on a Worksheet

————————————————————————————————

Contents:

Forms in Excel

ActiveX controls, Form controls & AutoShapes in an Excel Worksheet

Shape object & OLEObject object

ActiveX Controls in VBA

Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet

Illustrating Form Controls, ActiveX Controls & AutoShapes:

Button (Form Control); Command Button (ActiveX Control)

Check Box — Form Control or ActiveX Control

List Box & Combo Box — Form Control / ActiveX Control

Option Button — Form Control or ActiveX Control

Toggle Button — ActiveX Control

ScrollBar & SpinButton Controls — Form Control or ActiveX Control

TextBox — ActiveX Control

Label — Form Control or ActiveX Control

Illustrating Auto Shapes, Add a connector

————————————————————————————————

You can create various types of Forms in Excel, which are documents having a standard structure & format & help to organize, capture & modify data. Type of forms which can be created in Excel include: Data Form, Worksheet containing Form controls & ActiveX controls, & UserForms in VBA. You may use a Form individually, or combine them in various manners for your suitability. In this section we explain the Shape object & OLEObject object, and illustrate using ActiveX Controls, Form controls & AutoShapes in an Excel Worksheet.

Built-in Excel Data Form

Using a Data Form is an easy way to display or enter all information in one row in a table or in a range, without scrolling or moving between columns. A Data Form is best used: (i) when your spreadsheet is too big & you constantly scroll back & forward to display & enter data; (ii) when you want to view a simple form containing text boxes labeled on column headings, wherein each text box displays the row data for each column; & (iii) when you do not need advanced form features like a list box or spin button.

Excel has a built-in Data Form which can be generated automatically for your table or range listing all the table fields: all columns headers are displayed as labels for text boxes in one dialog box; each text box displays the row data for each column upto a maximum of 32 columns; you may enter new rows, update or delete rows, scroll through the records using the scroll bar, find previous or next rows based on specified criteria or cell contents; only formula result is displayed in text box for cells with formulas; Data Form cannot be printed though you may use the PrtScr button to save an image.

Refer Image 1a: Cell J3 has been selected, and Data Form is generated by clicking on ‘Form’ button in the Quick Access Toolbar (to Add the Form button to the Quick Access Toolbar: click the arrow next to the ‘Quick Access Toolbar’ > click ‘More Commands’ > click ‘All Commands’ in the ‘Choose commands from box’ > select the ‘Form’ button > click ‘Add’ > click ‘OK’). Image 1a displays the first row data in the Data Form: to navigate through one row at a time you may use the vertical scroll arrows in the center or click the Find Prev or Find Next (clicking the scroll bar in the area between the arrows will move through 10 rows in one go); to find the next or previous row as per criteria or cell contents — click Criteria, enter criteria (say Male in the Gender text box), click Find Next, and then the next row corresponding to Male Gender will be displayed; click on New or Delete to add new row or delete existing row; to change row data — press TAB to move to the next field in the row & press SHIFT+TAB to move to the previous field, enter new content in the field or text box, press Enter and the data will be updated & you will go the next row — clicking on Restore before pressing Enter will restore the old content; click Close to close the Data Form. Note that only formula result is dsplayed in text box for BMI column header whose cells have formulas, wherein the formula cannot be changed using the data form. When you enter Criteria, you may use the following wildcard characters: ? (question mark) > to find any single character viz. T?m finds both Tim & Tom; * (asterik) > to find any number of characters viz. *Active finds both InActive and VeryActive; ~ (tilde) followed by ?, *, or ~ > to find a question mark, asterik or tilde viz. When~? finds When?.

UserForms in Excel VBA

UserForm is a customized user interface (viz. custom dialog box), developed in VBA. It enables a user to interact, using a Form, in an organized and logical manner, to make data entry or for data retrieval with an Excel worksheet or to run a VBA application. UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Refer our separate section on Userforms for detailed illustration.

ActiveX controls, Form controls & AutoShapes in an Excel Worksheet

Another type of form is a worksheet: you can enter, format & view data in worksheet cells which can also be used as text boxes or labels by adjusting their height / width, so as to function as a data form; a worksheet can be used as an advanced data form by using its various built-in features which behave like controls, viz. comments, data validation, hyperlinks, background images, conditional formatting, embedded charts, AutoFilter, etc.

Two types of controls are available in Excel — Form controls & ActiveX Controls. Besides these controls, you can also add objects from the Drawing tools, like AutoShapes, WordArt, SmartArt graphic or text boxes. These controls & drawing tools add flexibility to using the worksheet as they can be linked to & work in tandem with worksheet cells — a check box control can be used to make multiple selections, an option button control allows to choose a single option from within a set of mutually exclusive choices, a spin button control facilitates to enter a number, & so on. These controls & objects can be displayed with associated labels / text & independent of row or column outlines / sizes, these may be linked to worksheet cells with our without using vba code, and can float freely or else move & resize with cells, for example, in respect of a command box control you may want to keep it the same size & in a specific location always so that when its underlying cells’ size changes or cells are moved, the command box retains its size & position.

Form Controls

Form controls are used to reference & interact with cell data in a worksheet — they are used to easily place values in worksheet cells, without programming, and they facilitate to compel users choose from defined options. VBA code is not required to use Form controls, but you can assign a macro to a control so that on clicking the control the macro will be executed. Form controls can also be added to chart sheets, but not to UserForms or to control events. For example, you may link a worksheet cell to a spin button, so that clicking on the up arrow will increase the value (increment a number, time or date) in the linked cell while clicking on the down arrow will decrease the value — this will obviate the need for manual entry in the cell. The Form controls — ‘Text Field’, ‘Combo List — Edit’, ‘Combo Drop-Down — Edit’, ‘Run Dialog’ — can only be used in Excel version 5.0 dialog sheets & are not available in Excel 2007. The various Form controls are illustrated later in this section.

ActiveX Controls

ActiveX controls can be used with VBA code or without, either directly on worksheets, while some can be used only on VBA UserForms. ActiveX controls offer more flexibility as compared to Form controls as they have numerous properties which can be used to customize their functionality, appearance, fonts & other characteristics.

ActiveX controls have associated event procedures which are triggered on clicking the control. ActiveX controls can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control. You cannot assign a macro to ActiveX controls similar to Form controls wherein clicking the control executes the macro. ActiveX controls cannot be added to chart sheets or to XLM macro sheets. ActiveX controls contained in your computer include Calendar Control 12.0 & Windows Media Player, as installed by Excel or other programs.

In Excel 2007 Form Controls & ActiveX Controls are available in the Controls group on the Developer tab of the Ribbon (Refer Image 1b), while in earlier versions they were available on toolbars.

Objects from the Drawing tools

In Excel 2007, under the Insert tab on the ribbon, you can insert an Object, Shape, Picture, SmartArt graphic, Chart, Text Box, WordArt, etc. in a worksheet. Right click on the object, shape or graphic you have inserted, and select Assign Macro which opens the Assign Macro dialog box from where you can select and assign a macro to the object. In this section, we limit our discussion to AutoShapes (we have a separate section which deals with Charts in detail). You can select from a set of ready-made shape types for an AutoShape object in vba, as specified in MsoAutoShapeType Enumeration, for use in your worksheet. VBA allows you to add shapes & objects which can be manipulated & formatted by resizing or rotating, adding text or caption & setting font, changing color, or adding 3D effects such as beveling & shadows, and assigning macros.

Shape object & OLEObject object

A Shape object represents an object in the drawing layer, such as an AutoShape, freeform, OLEobject or picture. Every excel worksheet  & chart sheet & excel chart has a drawing layer upon which drawing objects are placed. Both the Worksheet object & the Chart object both have a Shapes property that returns a Shapes collection ie. the Shapes object, which contains all the Shape objects in the worksheet or in the chart sheet. The you have the ShapeRange collection (ie. ShapeRange object), which represents a subset of shapes on a document — a ShapeRange object can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document. The ShapeRange object allows you to set the properties of a subcollection of all Shape objects. We have now discussed 3 objects: (i) Shape object; (ii) Shapes object; & (iii) ShapeRange object.

An OLEObject object represents an ActiveX control or a linked or embedded OLE object on a worksheet. The OLEObjects collection (ie. OLEObjects Object) contains all the OLEObject objects on a single worksheet. Use the Worksheet.OLEObjects method to return either a single OLE object (an OLEObject ) or a collection of all OLE objects (an OLEObjects Object) — Syntax: Worksheet.OLEObjects(Index), where Index is the name or number of the OLE object. Use the OLEObjects.ShapeRange Property to return a ShapeRange object which represents the specified object or objects — a subset of shapes which can be a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes. Note: OLE objects do not support many changes which can be made through ShapeRange. In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, but the OLEObject object is not used for Form Controls.

OLE — Object Linking and Embedding — is used to make content that is created in one program (ex. Microsoft Office Word) available in another program (ex. Microsoft Office Excel). OLE is supported by many different programs — only programs that are installed on your computer and which support OLE objects appear in the Object type box. Information may be copied as either a linked object or an embedded object — the prime difference between the two is where the data is stored & how the object is updated after it is placed in the destination file. Embedded objects are stored in the workbook in which they are inserted, & are not updated. Linked objects remain as separate files, & can be updated.

Shape.Type Property & Shape.FormControlType Property:

Use the Type Property of the Shape object to set or return the Shape Type, as per constants / values specified in the MsoShapeType Enumeration, Ex. the MsoShapeType constant msoFormControl indicates a Form Control, constant msoOLEControlObject indicates an OLE control object (ActiveX Control), and so on.

There is another property — FormControlType Property of the Shape object — which returns (read-only) the Control Type for a Shape object (per XlFormControl Enumeration) & this property is not valid for ActiveX controls but used only where the Shape.Type Property returns msoFormControl. Ex. the XlFormControl constant xlCheckBox represents a Check Box, constant xlListBox represents a List Box, and so on.

MsoShapeType Enumeration   XlFormControl Enumeration
MsoShapeType Value Description   XlFormControl Value Description
msoAutoShape 1 AutoShape       xlButtonControl      0 Button           
msoCallout 2 Callout   xlCheckBox 1 Check box
msoChart 3 Chart   xlDropDown 2 Combo box
msoComment 4 Comment   xlEditBox 3 Text box
msoFreeform 5 Freeform   xlGroupBox 4 Group box
msoGroup 6 Group   xlLabel 5 Label
msoEmbeddedOLEObject 7 Embedded OLE object   xlListBox 6 List box
msoFormControl 8 Form control   xlOptionButton 7 Option button
msoLine 9 Line   xlScrollBar 8 Scroll bar
msoLinkedOLEObject 10 Linked OLE object   xlSpinner 9 Spinner
msoLinkedPicture 11 Linked picture        
msoOLEControlObject 12 OLE control object        
msoPicture 13 Picture        
msoPlaceholder 14 Placeholder             
msoTextEffect 15 Text effect        
msoMedia 16 Media        
msoTextBox 17 Text box        
msoScriptAnchor 18 Script anchor        
msoTable 19 Table        
msoCanvas 20 Canvas        
msoDiagram 21 Diagram        
msoInk 22 Ink        
msoInkComment 23 Ink comment        
msoIgxGraphic 24 SmartArt graphic        
msoShapeTypeMixed -2 Mixed shape type        

Sub Shape_Type_FormControlType()

‘returns 12 indicating an OLE control object (MsoShapeType constant of msoOLEControlObject)

MsgBox Sheets(«Sheet1»).Shapes(«OptionButton1»).Type

‘returns the message «Check Box Form Control», indicating the shape is a Form Control & is a Check Box

If Sheets(«Sheet2»).Shapes(«Check Box 1»).Type = msoFormControl Then

If Sheets(«Sheet2»).Shapes(«Check Box 1»).FormControlType = xlCheckBox Then MsgBox «Check Box Form Control»

End If

End Sub

Example: for Auto Shapes, illustrating Shapes object, Shape object & ShapeRange object

Sub AutoShape_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Auto Shapes — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 7 auto shapes, in this order: Rectangle 1, Rectangle 2, Oval 1, Rounded Rectange 1, Triangle 1, Oval 2, Triangle 2

Dim ws As Worksheet, shp As Shape

Set ws = Sheets(«Sheet1»)

‘———————————

‘refer Shapes collection ie. Shapes object

‘returns 7 (there are seven shapes in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘refer each Shape object

For Each shp In ws.Shapes

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

Next

‘———————————

‘ShapeRange object

‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)

‘using the Array function to construct an array of index numbers — set the fill forecolor for shapes one & four (Rectangle 1 & Rounded Rectange 1)

ws.Shapes.Range(Array(1, 4)).Fill.Solid

ws.Shapes.Range(Array(1, 4)).Fill.ForeColor.RGB = RGB(255, 0, 0)

‘using the Array function to construct an array of names — set the height for shapes named Rectangle 2 & Triangle 1 (shapes 2 & 5)

ws.Shapes.Range(Array(«Rectangle 2», «Triangle 1»)).Height = 20

‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Oval 1)

ws.Shapes(3).TextFrame.Characters.Text = «Oval Shape«

‘activate sheet

ws.Activate

‘select shapes sixth & seventh (Oval 2, Triangle 2)

ActiveSheet.Shapes.Range(Array(6, 7)).Select

‘using the ShapeRange property of the Selection object to return all shapes in the selection

ActiveWindow.Selection.ShapeRange.Fill.Solid

ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 255, 0)

‘return a single shape (seventh shape — Triangle 2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

ActiveWindow.Selection.ShapeRange(2).TextFrame.Characters.Text = «Triangle«

End Sub

Example: for Form Controls, illustrating Shapes object, Shape object & ShapeRange object

Sub FormControls_ShapesObj_ShapeObj_ShapeRangeObj()
‘illustrating Form Controls — Shapes object, Shape object & ShapeRange object
‘Sheet1 contains 5 Form Controls, in this order: Button 1, Check Box 1, Option Button 1, Scroll Bar 1, Label 1

Dim ws As Worksheet, shp As Shape

Set ws = Sheets(«Sheet1»)

‘———————————

‘refer Shapes collection ie. Shapes object

‘returns 5 (there are seven shapes — Form Controls — in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘refer each Shape object

For Each shp In ws.Shapes

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

Next

‘———————————

‘ShapeRange object

‘use the Range property to return multiple number of shapes — return a set of Shapes by specifying Name or Index Number — Shapes.Range(index)

‘using the Array function to construct an array of index numbers — set the Left property for shapes one & four (Button 1 & Scroll Bar 1)

ws.Shapes.Range(Array(1, 4)).Left = 25

‘using the Array function to construct an array of names — set the height for shapes named Check Box 1 & Option Button 1 (shapes 2 & 3)

ws.Shapes.Range(Array(«Check Box 1», «Option Button 1»)).Height = 20

‘for a single member of the collection, it is easier to use the Item method than using the Range property — set caption / text for the third shape (Option Button 1)

ws.Shapes(3).TextFrame.Characters.Text = «SelectOption«

‘activate sheet

ws.Activate

‘select shapes second & third (Check Box 1 & Option Button 1)

ActiveSheet.Shapes.Range(Array(2, 3)).Select

‘using the ShapeRange property of the Selection object to return all shapes in the selection — set a solid fill forecolor

ActiveWindow.Selection.ShapeRange.Fill.Solid

ActiveWindow.Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 0, 0)

‘return a single shape (third shape — Option Button 1) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

‘set Option Button’s border line: as dash-dash-dot, thickness of 2 pts & color green

ActiveWindow.Selection.ShapeRange(2).Line.DashStyle = msoLineDashDotDot

ActiveWindow.Selection.ShapeRange(2).Line.Weight = 2

ActiveWindow.Selection.ShapeRange(2).Line.ForeColor.RGB = RGB(0, 255, 0)

End Sub

Example: for ActiveX Controls, illustrating Shapes object, Shape object & ShapeRange object

Sub ActiveXControls_OLEObjects_OLEObject_ShapeRangeObject()
‘illustrating ActiveX Controls — OLEObjects object, OLEObject object & ShapeRange object
‘Sheet1 contains 7 OLEObjects, in this order: ComboBox1, ListBox1, CommandButton1, OptionButton1, CheckBox1, SpinButton1, CommandButton2

Dim ws As Worksheet, obj As OLEObject

Set ws = Sheets(«Sheet1«)

‘Count the no. of OLEObjects in the OLEObjects collection — returns 7

MsgBox ws.OLEObjects.Count

‘refer each OLEObject object in worksheet

For Each obj In ws.OLEObjects

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

obj.Placement = xlFreeFloating

Next

‘Set the height of the OLEObject named CommandButton2

ws.OLEObjects(«CommandButton2»).Height = 30

‘———————————

‘ShapeRange object — OLE objects do not support many changes which can be made through ShapeRange

‘activate sheet

ws.Activate

‘select OLEObjects third & seventh (CommandButton1, CommandButton2)

ActiveSheet.OLEObjects(3).Select (True)

ActiveSheet.OLEObjects(7).Select (False)

‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set shadow

ActiveWindow.Selection.ShapeRange.Shadow.Visible = True

‘using the ShapeRange property of the Selection object to return all OLEObjects in the selection — set height, in points

ActiveWindow.Selection.ShapeRange.Height = 20

‘return a single OLEObject (seventh OLEObject — CommandButton2) in the selection, by using Selection.ShapeRange(index), where index is the shape name or the index number

‘set the distance, in points, from the top edge of the object to the top of worksheet’s row 1

ActiveWindow.Selection.ShapeRange(2).Top = 270

End Sub

ActiveX Controls in VBA

By default, a control’s name (ie. code name) is based on its type ex. default name of a CommandButton is CommandButton1, second CommandButton will be CommandButton2, & so on. Every control name should be unique in a worksheet. An ActiveX control’s name is visible at the top of the Properties window (in the drop-down list where control is selected) where on the right is the control type (ex. CommandButton) and on its left is the name of the control (ex. CommandButton1). The control name (ie. CommandButton1) can be viewed & changed in the sheet’s Name box and also in the cell to the right of (Name) in the Properties window. You may also change the control name in code, using its Name property. Note that control name is different from its Caption, which is the text that may appear on the control.

ActiveX controls can be referred by name — the control name should be qualified with the sheet name when used from a module outside the sheet that contains the control. Control name is used to return the control from the Shapes or OLEObject collection ex. Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).Shapes(«CommandButton1»).Height = 20. Names of event procedures also correspond to the control’s name (ex. CommandButton1_Click).

ActiveX controls have associated event procedures which are triggered on clicking the control (you cannot assign any arbitrary macro to ActiveX controls like you do to Form controls). Event-handler procedures must be located in the code module of the object (viz. worksheet, UserForm) containing the control, or written in class modules. On top of the  code module, there are two drop-down boxes — selecting the control on the left will display the events on the right which are supported for that control. For example, a CommandButton control generates a Click event for which an event-handler sub procedure can be written as follows viz. clicking the CommandButton control (control name CommandButton1) will enter «Hello» in cell A1 of the sheet which contains the control & return this text in a message box:

Private Sub CommandButton1_Click()

Range(«A1»).Value = «Hello«

MsgBox Range(«A1»).Value

End Sub

Accessing ActiveX Control Properties in VBA 

Note: All illustrations below relate to the ActiveX control of CommandButton named «CommandButton1».

In VBA code, ActiveX controls can be referred by name & you may thus set the control properties, for example, to set the mouse pointer for CommandButton named «CommandButton1»:

Sheets(«Sheet1»).CommandButton1.MousePointer = fmMousePointerIBeam.

In Excel VBA, ActiveX controls are represented by OLEObject objects in the OLEObjects collection, so that ActiveX control properties can be set using the properties of an OLEObject object, for example:

Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Top = 25 or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).BottomRightCell.Interior.Color = RGB(255, 255, 0).

If the control property is listed in the Object Browser (in VBE, click View & then click Object Browser) under the class OLEObject, then you may use the OLEObject from the OLEObjects collection object, to set the property, otherwise (if the property is not listed under the OLEObject class in the Object Browser), then you must return the actual control object by using the Object property of the OLEObject object, for example to set the BackColor or the Caption property:

Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.BackColor = RGB(255, 255, 0) or Sheets(«Sheet1»).OLEObjects(«CommandButton1»).Object.Caption = «Click to Run«.

Because an OLEObject object is also a member of the Shapes collection, many ActiveX control properties can be set using the properties of a Shape object, ex.

Dim sh As Shape
‘set sh to an existing CommandButton ActiveX control
Set shp = Sheets(«Sheet4»).Shapes(«CommandButton1»)
‘Type Property can be used only with the Shape object

If shp.Type = msoOLEControlObject Then

shp.Height = 26
shp.Placement = xlFreeFloating

shp.Locked = True

End If

Add an ActiveX Control, a Form Control or an AutoShape, in Worksheet

Add a new OLE object to an Excel sheet

Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object. Syntax: OLEObjects.Add(ClassType, FileName, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify. It is necessary to specify either the ClassType argument — which specifies the programmatic identifier (see below), as a string value, for the new object being added — or the FileName argument — which specifies the file name, as a string value, that is used to add the new object. Specifying the ClassType argument will ignore the FileName & Link arguments. Setting the Link argument to True will link the new object to the file whose FileName is specified whereas the False (default) setting will add the new object as a copy of the file without linking.

The new object will display as an icon or picture by setting the DisplayAsIcon argument to True, & in this case you can specify the icon by using the arguments of IconFileName & IconIndex. Only when the DisplayAsIcon argument is set to True, can you use the IconFileName argument to specify the file name containing the icon to be displayed & omitting this argument will display the default OLE class icon. Only when the DisplayAsIcon argument is set to True & the IconFileName argument specifies a valid file which contains icon(s), you can use the IconIndex argument to specify the number of the icon in the file & on non-existence of that index number the file’s first icon is used. Only when the DisplayAsIcon argument is set to True, can you use the IconLabel argument for specifying a string value to display a caption (or label) under the icon, & omitting this argument or setting it as an empty string («») will not display any caption.

The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.

OLE programmatic identifier — also called a ProgID — is used to create an Automation object. The following is a list OLE programmatic identifiers for ActiveX controls:

OLE programmatic identifier
Below control is created By using the below ProgID
CheckBox Forms.CheckBox.1                          
ComboBox                          Forms.ComboBox.1
CommandButton Forms.CommandButton.1           
Frame Forms.Frame.1
Image Forms.Image.1
Label Forms.Label.1
ListBox Forms.ListBox.1
MultiPage Forms.MultiPage.1
OptionButton Forms.OptionButton.1
ScrollBar Forms.ScrollBar.1
SpinButton Forms.SpinButton.1
TabStrip Forms.TabStrip.1
TextBox Forms.TextBox.1
ToggleButton Forms.ToggleButton.1

Example: add an ActiveX control, check box to Sheet1 — return an OLEObject representing the new OLE object:

Dim objChBx As OLEObject
Set objChBx = Sheets(«Sheet1″).OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox objChBx.Name
‘TypeName Function returns the data-type about a variable — TypeName(varname)
‘returns CheckBox — Object Property of the OLEObject returns a OLE Automation object associated with this OLE object
MsgBox TypeName(objChBx.Object)

You may also use the AddOLEObject Method of the Shapes object  to add a new OLEObject to a sheet — this method returns a Shape object representing the new OLE object. Syntax: Shapes.AddOLEObject(ClassType, Filename, Link, DisplayAsIcon, IconFileName, IconIndex, IconLabel, Left, Top, Width, Height). All arguments are optional to specify & work similar to the Add Method of the OLEObjects object, as explained above.

Example: add an ActiveX control, check box to Sheet1 — return a Shape Object representing the new OLE object:

Dim shChkBx As Shape
Set shChkBx = Sheets(«Sheet1″).Shapes.AddOLEObject(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=20, Top:=20, Width:=100, Height:=20)
MsgBox shChkBx.Name
‘Type Property can be used only with the Shape object
‘returns 12 — constant msoOLEControlObject indicating an OLE control object (ActiveX Control)
MsgBox shChkBx.Type 

Create a new Form Control

Use the Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height). All arguments are necessary to be specified. The Type argument specifies the type of the form control as per constants in the XlFormControl Enumeration. The Left & Top arguments specify the distance of the new object, in points, from the left edge of column A or from the top of row 1 on a worksheet respectively (or the distance from the left edge / top edge of a chart). The Width & Height arguments specify the width & height of the new object, in points.

Add a new AutoShape

Use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). All arguments are necessary to specify. The Type argument specifies the shape type per the MsoAutoShapeType Enumeration. The Left argument specifies the distance of the left edge of the AutoShape’s bounding box, in points, from the left edge of the document. The Top argument specifies the distance of the top edge of the AutoShape’s bounding box, in points, from the top edge of the document. The Width & Height arguments specify the width & height of the AutoShape’s bounding box, in points.

MsoAutoShapeType Enumeration: msoShape16pointStar (value 94 — 16pointStar), msoShapeBalloon (value 137 — Balloon), msoShapeCube (value 14 — Cube), msoShapeDiamond (value 4 — Diamond), msoShapeDownArrow (value 36 — block arrow pointing down), msoShapeRightArrow (value 33 — block arrow pointing right), msoShapeLeftRightArrow (value 37 block arrow with arrowheads that point both left & right), msoShapeHeart (value 21 — Heart), msoShapeHexagon (value 10 — Hexagon), msoShapeIsoscelesTriangle (value 7 — IsoscelesTriangle), msoShapeOval (value 9 — Oval), msoShapeRectangle (value 1 — Rectangle), and so on.

To change the AutoShape type (other than a line, freeform drawing, or connector), set the AutoShapeType Property of the Shape object (Syntax: Shape.AutoShapeType) using the MsoAutoShapeType Enumeration. The shape will retain its size, color & other attributes on changing its type.

Illustrating Form Controls, ActiveX Controls & AutoShapes

Button (Form Control); Command Button (ActiveX Control)

A Button (Form Control)  or a Command Button (ActiveX Control) is typically used to execute a macro when clicked by a user. You can assign a macro to the Button (Form Control) but cannot assign a macro to ActiveX controls similar to Form controls. CommandButton (ActiveX control) can have associated event procedures which are triggered on clicking the control.

CommandButton (ActiveX control) can be used to control different events, so that you can write macros to execute the associated events. You can execute different actions specific to the option selected by the user to interact with the control: you may write a macro associated with the Click event of the CommandButton so that clicking on the CommandButton will run the code which is attached to the Click event or you can insert the name of a macro to be run on clicking the CommandButton; similarly you may write a separate macro associated with another event of the CommandButton which will be executed likewise. To write a macro associated with the Click event of the CommandButton — in VBE (Visual Basic Editor) select the name of the CommandButton (in the code module of the worksheet containing the control) from the top-left dropdown of the code window and then select Click from the top-right dropdown.

CommandButton (ActiveX control) offers more flexibility as compared to Button (Form control), having numerous properties which can be used to customize its functionality, appearance, fonts & other characteristics, as illustrated by separate examples of Button & CommandButton below:

Example: Use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a

Sub FormControl_Button_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Button) — this returns a Shape object representing the new control — refer Image 2a

Dim shpBtn As Shape, rng As Range

Set rng = Sheets(«Sheet1»).Range(«A2»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 15

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 20

‘for an already existing Form Control shape — Button, with the name «Button 1»

‘Set shpBtn = Sheets(«Sheet1»).Shapes(«Button 1»)

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘set object variable to the newly added Button Form control — position & size the Button with the cell assigned to the rng variable

Set shpBtn = Sheets(«Sheet1«).Shapes.AddFormControl(Type:=xlButtonControl, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With shpBtn

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click To Run«

‘set a String value as object’s name

.Name = «Button 1«

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘reset shape height & width

.Width = rng.Width

.Height = rng.Height

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the NextStep macro

.OnAction = «NextStep«

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

‘this property is valid for Button (Form Control)
With .TextFrame

.HorizontalAlignment = xlHAlignCenter

.VerticalAlignment = xlVAlignDistributed

.Characters.Text = «ClickButton»

‘to set internal margins:

‘.AutoMargins = False

‘.MarginLeft = 0.25

‘.MarginRight = 0.1

‘.MarginTop = 0.2

‘.MarginBottom = 0.15

With .Characters(Start:=1, Length:=5).Font

.Name = «Arial«

.Bold = True

.ColorIndex = 3

.Size = 10

.Italic = True

End With

With .Characters(Start:=6, Length:=6).Font

.Name = «Calibiri«

.Bold = True

.Size = 10

.ColorIndex = 5

.Italic = False

.Underline = True

End With

End With

‘wrt to the cell which is under the upper-left corner of the object — set one cell below this

With .TopLeftCell.Offset(1, 0)

‘enter cell address in the cell

.Value = .Address

‘set cell color to green

.Interior.Color = RGB(0, 255, 0)

End With

End With

End Sub

Example: Add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b

Sub ActiveXControl_CommandButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CommandButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 2b

‘OLEObject is not used for Form Controls

Dim objCmdBtn As OLEObject, shpBtn As Shape

Dim ws As Worksheet, rng As Range

Set ws = Sheets(«Sheet1«)

ws.Activate

Set rng = Range(«A2«)

‘delete ActiveX Control CommandButton objects

For Each objCmdBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objCmdBtn.Object) = «CommandButton» Then objCmdBtn.Delete

Next objCmdBtn

‘delete Form Control Button objects

For Each shpBtn In ActiveSheet.Shapes

If shpBtn.Type = msoFormControl Then

If shpBtn.FormControlType = xlButtonControl Then shpBtn.Delete

End If

Next shpBtn

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 15

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 20

‘for an already existing ActiveX control, with the name «CommandButton1»

‘Set objCmdBtn = ws.OLEObjects(«CommandButton1»)

‘Use the Add Method of the OLEObjects object, to add a new OLEObject to a sheet — this method returns an OLEObject representing the new OLE object

‘set object variable to the newly added command button ActiveX control — position & size the CommandButton with the cell assigned to the rng variable

Set objCmdBtn = ws.OLEObjects.Add(ClassType:=»Forms.CommandButton.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objCmdBtn

‘set a String value as object’s name

.Name = «CommandButton1»

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

‘returns the index number of the object within the collection of similar objects

MsgBox .Index

‘reset left & right distance of command button relative to the worksheet’s left & top edge

‘.Left = 50

‘.Top = 50

‘reset size of command button

‘.Height = 25

‘.Width = 35

‘set shadow

.Shadow = True

‘wrt to the cell which is under the upper-left corner of the object — set cell on its right

With .TopLeftCell.Offset(0, 1)

‘enter cell address in the cell

.Value = .Address

‘set cell color to green

.Interior.Color = RGB(0, 255, 0)

End With

‘Object Property of the OLEObject returns a OLE Automation object associated with the OLE object (objCmdBtn)

With .Object

.WordWrap = True

.MousePointer = fmMousePointerCross

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg«)

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

.Caption = «Click«

‘set back color to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to blue

.ForeColor = RGB(0, 0, 255)

‘for BackStyle, use fmBackStyleOpaque or fmBackStyleTransparent

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

End Sub

Check Box — Form Control or ActiveX Control

With Check Box, user can select multiple options at a time on a worksheet or in a group box, by selecting each Check Box against which an option is available. CheckBox can be used in a singular manner viz. a single Check Box can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. The Value property of a CheckBox indicates whether it is selected or not. A True value indicates that the CheckBox is selected, False indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set (can be set either in the Properties window or by using a macro or vba code) to True for the CheckBox to have a Null value. Option Buttons on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options — Option Button gets deselected only on selection of another Option Button and not by clicking itself.

Below we illustrate: (i) a Form Control Check Box & and assign it to a Macro; and (ii) an ActiveX Control CheckBox & a Macro associated with the Click event of this CheckBox.

Example: Form Control Check Box(es) & Macro to which they are assigned:

(1) Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a

Sub FormControl_CheckBox_Shape_Properties_1()
‘Add a Form Control Check Box with the CheckBoxes.Add Method, set properties for the Form control (CheckBox) object — Refer Image 3a

Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate
‘————————

‘a quick way of adding multiple checkboxes (Form Control) in a worksheet & then deleting:

‘Dim cell As Range, rng As Range

‘Set rng = Range(«J5:J10»)

‘Set ws = Sheets(«Sheet4»)

‘ws.Activate

‘For Each cell In rng

‘With ws.CheckBoxes.Add(cell.Left, cell.Top, cell.Width, cell.Height)

‘.Characters.Text = cell.Address

‘End With

‘Next

‘ws.CheckBoxes.Delete

‘————————

Set rng = ws.Range(«B2»)

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘delete Form Control CheckBox objects

For Each shpChBx In ActiveSheet.Shapes

If shpChBx.Type = msoFormControl Then

If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete

End If

Next shpChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘add a check box Form control — position & size the Check Box with the cell assigned to the rng variable

ws.CheckBoxes.Add(Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height).Select

With Selection

‘set a String value as object’s name

.Name = «Check Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Display3DShading = False

‘True (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object

.Enabled = True

‘check box will be printed when the document is printed

.PrintObject = True

.linkedCell = rng.Address

‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox

.TopLeftCell.Offset(0, -1) = «Select Country«

‘Value property of a CheckBox indicates whether it is selected or not.

.Value = xlOn

‘.Value = xlOff

‘specify caption text

.Characters.Text = «USA«

‘alternatively:

‘.Caption = «USA«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

.OnAction = «ChkBoxClick«

‘a ShapeRange object represents a subset of shapes on a document — it can contain a single shape, or a few shapes (viz. first, third & fifth shape out of a total of 8 shapes in a sheet), or it could represent all shapes in a document

With .ShapeRange

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for check box

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

End With

‘—————————

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

ws.Shapes(«Check Box 1»).Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «Check Box 2«

Selection.linkedCell = rng.Offset(1, 0).Address

Selection.Caption = «UK«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

Selection.OnAction = «ChkBoxClick«

‘—————————

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.WrapText = True

.Interior.Color = RGB(0, 255, 0)

.Borders.LineStyle = xlContinuous

.Borders.ColorIndex = 5

.Borders.Weight = xlMedium

End With

End Sub

(2) Use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object

Sub FormControl_CheckBox_Shape_Properties_2()
‘use Shapes.AddFormControl Method to create an Excel Form Control (check box) — this returns a Shape object representing the new control — set properties for the Form control (CheckBox) object — Refer Image 3a

Dim shpChBx As Shape, ws As Worksheet, rng As Range, objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«B2»)

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘delete Form Control CheckBox objects

For Each shpChBx In ActiveSheet.Shapes

If shpChBx.Type = msoFormControl Then

If shpChBx.FormControlType = xlCheckBox Then shpChBx.Delete

End If

Next shpChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘for an already existing Form Control shape — Check Box, with the name «Check Box 1»

‘Set shpChBx = ws.Shapes(«Check Box 1»)

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘set object variable to the newly added check box Form control — position & size the Check Box with the cell assigned to the rng variable

Set shpChBx = ws.Shapes.AddFormControl(xlCheckBox, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With shpChBx

‘set a String value as object’s name

.Name = «Check Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘specify caption text

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘use the .OLEFormat.Object object to manipulate Display3DShading

.OLEFormat.Object.Display3DShading = False

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

.OnAction = «ChkBoxClick«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

‘True  (for Enabled Property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys).

‘enable the object

.Enabled = True

‘check box will be printed when the document is printed

.PrintObject = True

.linkedCell = rng.Address

‘Value property of a CheckBox indicates whether it is selected or not.

.Value = xlOn

‘.Value = xlOff

End With

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for check box

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

‘————————————-

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

ws.Shapes(«Check Box 1»).Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «Check Box 2«

Selection.linkedCell = rng.Offset(1, 0).Address

Selection.Characters.Text = «UK«

‘alternatively

‘Selection.Caption = «UK«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ChkBoxClick macro

Selection.OnAction = «ChkBoxClick«

‘enter text in the same row to the left of the checkbox

rng.Offset(0, -1) = «Select Country«

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.WrapText = True

.Interior.Color = RGB(0, 255, 0)

.Borders.LineStyle = xlContinuous

.Borders.ColorIndex = 5

.Borders.Weight = xlMedium

End With

End Sub

Use with (1) or (2) above: Macro to which the Form Control Check Boxes are assigned — this procedure is located in a standard module of the workbook & executes on clicking the Form Control check boxes («Check Box 1» & «Check Box 2»)

Sub ChkBoxClick()

On Error Resume Next

Dim shpChBx1 As Shape, shpChBx2 As Shape, ws As Worksheet

Set ws = Sheets(«Sheet4»)

ws.Activate

Set shpChBx1 = ws.Shapes(«Check Box 1»)

Set shpChBx2 = ws.Shapes(«Check Box 2»)

If shpChBx1.ControlFormat.Value = xlOn Then

If shpChBx2.ControlFormat.Value = xlOff Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If shpChBx2.ControlFormat.Value = xlOff Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

End If

End If

End Sub

Example: ActiveX Control CheckBox(es) & Macro associated with the Click event of the CheckBox:

Add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b

Sub ActiveXControl_CheckBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (CheckBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 3b

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objChBx As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«B2»)

‘delete Form Control CheckBox objects in worksheet

ws.CheckBoxes.Delete

‘delete ActiveX Control CheckBox objects

For Each objChBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objChBx.Object) = «CheckBox» Then objChBx.Delete

Next objChBx

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rng.ColumnWidth = 10

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rng.RowHeight = 15

‘for an already existing ActiveX control checkbox, with the name «CheckBox1»

‘Set objChBx = ws.OLEObjects(«CheckBox1»)

‘set object variable to the newly added check box ActiveX control — position & size the CheckBox with the cell assigned to the rng variable

Set objChBx = ws.OLEObjects.Add(ClassType:=»Forms.CheckBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objChBx

‘set a String value as object’s name

.Name = «CheckBox1«

‘returns the index number of the object within the collection of similar objects

MsgBox .Index

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlMove

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘True (for Enabled property) indicates that the control can be accessed through a vba code & respond to user-generated events (ie. the user can interact with the control by using mouse, keystrokes, accelerators, or hotkeys) — enable the object

.Enabled = True

‘this property is ignored by ActiveX controls because these controls always load when a workbook is opened

.AutoLoad = True

‘check box will be printed when the document is printed

.PrintObject = True

‘ControlSource Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘.LinkedCell = «Sheet1!B2«

.linkedCell = rng.Address

‘wrt to the cell which is under the upper-left corner of the checkbox — enter text in the same row to the right of the checkbox

.TopLeftCell.Offset(0, -1) = «Country«

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘will enable CheckBox to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a CheckBox indicates whether it is selected or not. True (integer value 1) indicates that the CheckBox is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the CheckBox will appear shaded in this case. The value of TripleState property should be set to True for the CheckBox to have a Null value.

.Value = True

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify how caption will appear relative to the control

.Alignment = fmAlignmentLeft

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «USA«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

‘——————————

‘copy check box and create new check box with same properties

‘set range size, for cell below the existing check box

rng.Offset(1, 0).ColumnWidth = rng.ColumnWidth

rng.Offset(1, 0).RowHeight = rng.Height

‘copy check box to clipboard

.Copy

‘paste a copy of the checkbox in the same sheet

ws.Paste

‘fit new check box in the cell below the existing check box

Selection.Left = rng.Offset(1, 0).Left

Selection.Top = rng.Offset(1, 0).Top

Selection.Name = «CheckBox2«

ws.OLEObjects(«CheckBox2»).linkedCell = rng.Offset(1, 0).Address

ws.OLEObjects(«CheckBox2»).Object.Caption = «UK«

‘——————————

‘merge & format cells to the left of both check boxes

Union(rng.Offset(0, -1), rng.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

End With

End Sub

Macro associated with the Click event of the CheckBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox1)

Private Sub CheckBox1_Click()

On Error Resume Next

If CheckBox1.Object.Value = True Then

If CheckBox2.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If CheckBox2.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

End If

End If

End Sub

Macro associated with the Click event of the CheckBox2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (CheckBox2)

Private Sub CheckBox2_Click()

On Error Resume Next

If CheckBox2.Object.Value = True Then

If CheckBox1.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»UK«

Else

Range(«$A$5:$B$13»).AutoFilter Field:=1

End If

Else

If CheckBox1.Object.Value = False Then

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»«

Else

Range(«$A$5:$B$13″).AutoFilter Field:=1, Criteria1:=»USA«

End If

End If

End Sub

List Box & Combo Box — Form Control / ActiveX Control

A List Box or Combo Box is a list of items from which a user can select. They facilitate in accepting data from users and making entries in an Excel worksheet. List box may be of 3 types: (i) a single-selection list box which allows selection of a single item only; (ii) A multiple-selection list box which allows selection of one or more contiguous (adjacent) items; (iii) An extended-selection list box which allows selection of either a single item, or selection of multiple contiguous or noncontiguous items.

Difference between List Box and Combo Box:
1. The Combo Box is a drop-down list (the user-entered item or the list-selected item is visible in the text area, whereas list values are visible by using the drop-down), while a List Box shows a certain number of values with or without a scroll bar. In a Combo Box, only one row of items is visible at a given time (without using the drop-down) whereas in a List Box one or more can be visible at a time.
2. In a Combo Box you can select ony one option from the list, while in a List Box you can select multiple options from the list.
3. The user can enter his own item (in text area) in a ComboBox if it is not included in the list, which is not possible to do in a List Box. In this sense, Combo Box is a combination of Text Box and List Box.
4. Check Box can be used within List Box, but not within Combo Box. List Box allows you to display a check box next to each item in the list, to enable user to select items (this might be easier for the user than using the multiple selection methods).

Below we illustrate: (i) a Form Control List Box & and assign it to a Macro; and (ii) an ActiveX Control ListBox & a Macro associated with the Click event of this ListBox.

Example: Form Control List Box & Macro to which it is assigned:

Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a

Sub FormControl_ListBox_Shape_Properties_1()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 4a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, objListBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete ActiveX Control ListBox objects

For Each objListBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objListBx.Object) = «ListBox» Then objListBx.Delete

Next objListBx

‘delete Form Control ListBox objects

For Each shpListBx In ActiveSheet.Shapes

If shpListBx.Type = msoFormControl Then

If shpListBx.FormControlType = xlListBox Then shpListBx.Delete

End If

Next shpListBx

Set rngSource = Range(«A3:A7»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngListBx.ColumnWidth = 11

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBx.RowHeight = 30

‘for an already existing Form Control shape — ListBox, with the name «List Box 1»

‘Set shpListBx = ws.Shapes(«List Box 1»)

‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘to remove all items from listbox (not required for the newly created list box):

With shpListBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.

For i = .ControlFormat.ListCount To 1 Step -1

‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.

.ControlFormat.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

.AlternativeText = «LB«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = False

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ControlFormat.ListFillRange = rngSource.Address

‘alternatively:

‘.ControlFormat.ListFillRange = «$A$2:$A$7«

‘.ControlFormat.ListFillRange = Range(«A2:A7»).Address

‘.ControlFormat.ListFillRange = «NamedRange«

‘———————

‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)

‘fill ListBox

‘.OLEFormat.Object.List = rngSource.Value

‘.OLEFormat.Object.List = Range(«A2:A7»).Value

‘replace value of the second item in the list, after folling listbox using the ControlFormat.List Method:

‘.OLEFormat.Object.List(2) = «ChangeItem«

‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)

‘return first item:

MsgBox .ControlFormat.List(1)

‘alternatively — return first item:

MsgBox .OLEFormat.Object.List(1)

‘———————
‘ControlFormat.MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) xlNone, the default setting, wherein only a single item can be selected; (ii) xlSimple which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) xlExtended which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.

.ControlFormat.MultiSelect = xlNone

‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.

.ControlFormat.ListIndex = 3

‘return selected item from ListBox ie. the value of list box — cannot be used with a multi-select ListBox

MsgBox .ControlFormat.List(.ControlFormat.ListIndex)

‘or:

‘return selected item(s) from ListBox — this can be used with a multi-select ListBox

‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list

For i = 1 To .ControlFormat.ListCount

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

If .OLEFormat.Object.Selected(i) Then

MsgBox .ControlFormat.List(i)

End If

Next i

‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)

MsgBox .ControlFormat.Value

‘use the ControlFormat.LinkedCell property (not valid for a multi-select ListBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)

‘enter the selection’s list position to a specific cell

.ControlFormat.linkedCell = rngListBx.Address

‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item

rngListBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngListBx.Value)

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ListBox_Change macro

.OnAction = «ListBox_Change»

End With

‘call the assigned macro

Call ListBox_Change

End Sub

Macro to which the Form Control ListBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «List Box 1» value

Sub ListBox_Change()
‘this macro has been assigned to the «List Box 1» & will execute when the listbox value changes

Dim shpListBx As Shape, ws As Worksheet

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set object variable to an existing Form Control shape — ListBox

Set shpListBx = ws.Shapes(«List Box 1»)

‘call the Sales_Region sub — argument / value is being supplied by this code to the Sales_Region procedure when it is called

‘when arguments are passed to a procedure from other procedures, then these are listed or declared between the parentheses viz. shpListBx.ControlFormat.Value

Call Sales_Region(shpListBx.ControlFormat.Value)

End Sub

This procedure is located in a standard module of the workbook & is called by the above macro (to which the Form Control ListBox is assigned)

Sub Sales_Region(i As Integer)
‘an external argument (Integer value) supplied by the calling sub (ListBox_Change) is used by this procedure to perform an action

If i = 1 Then

Call Sales_Total(«I»)

ElseIf i = 2 Then

Call Sales_Total(«G»)

ElseIf i = 3 Then

Call Sales_Total(«H»)

ElseIf i = 4 Then

Call Sales_Total(«E»)

ElseIf i = 5 Then

Call Sales_Total(«F»)

End If

    End Sub

This procedure is located in a standard module of the workbook & is called by the above macro

Sub Sales_Total(letter As String)
‘an external argument (String value) supplied by the calling sub (Sales_Region) is used by this procedure to perform an action

Dim shpListBx As Shape, ws As Worksheet, rng As Range, str As String

Set ws = Sheets(«Sheet1»)

Set shpListBx = ws.Shapes(«List Box 1»)

‘linked cell of listbox as a string value

str = shpListBx.ControlFormat.linkedCell

‘set range of linked cell

Set rng = ws.Range(str)

rng.Offset(2, 0).Value = ws.Range(«$» & letter & «$7»).Value

rng.Offset(2, 0).Interior.Color = RGB(0, 255, 0)

End Sub

Example: Create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control

Sub FormControl_ListBox_Shape_Properties_2()
‘create an Excel Form Control (list box) & set ListBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim shpListBx As Shape, ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A3:A7»)

rngListBx.ColumnWidth = 11

rngListBx.RowHeight = 30

‘set object variable to the newly added ListBox Form control — position & size the ListBox with the cell assigned to the rngListBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control

Set shpListBx = ws.Shapes.AddFormControl(xlListBox, Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘remove all items from listbox (not required for the newly created list box):

With shpListBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

.ControlFormat.RemoveAllItems

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will not retain its original proportions when it is resized

.LockAspectRatio = msoFalse

.AlternativeText = «LB«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = False

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.ControlFormat.AddItem rngSource(i, 1).Value

Next i

‘alternatively:

‘With .ControlFormat

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘End With

‘xlSimple allows multiple selections

.ControlFormat.MultiSelect = xlSimple

‘Select multiple items in the ListBox

For i = 1 To .ControlFormat.ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.OLEFormat.Object.Selected(i) = True

End If

Next i

End With

End Sub

Example: Create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method

Sub FormControl_ListBox_Properties_3()
‘create an Excel Form Control (list box) — add a new listbox using ListBoxes.Add method
‘Forms ListBox allows a single column, use an ActiveX ListBox for multi columns

Dim ws As Worksheet, rngListBx As Range, rngSource As Range, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBx = ws.Range(«A10»)

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A3:A7»)

rngListBx.ColumnWidth = 11

rngListBx.RowHeight = 30

‘position & size the ListBox with the cell assigned to the rngListBx variable

‘add a new listbox — ListBoxes.Add:

ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height).Select

With Selection

‘alternatively:

‘With ws.ListBoxes.Add(Left:=rngListBx.Left, Top:=rngListBx.Top, Width:=rngListBx.Width, Height:=rngListBx.Height)

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box or a combo box (not required for the newly created list box)

If .ListFillRange = «« Then

‘RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

.RemoveAllItems

Else

‘clear ListBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «List Box 1«

.Placement = xlFreeFloating

‘use the Locked Property to lock — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘turn 3D Shading Off

.Display3DShading = False

‘enable the object

.Enabled = True

‘set PrintObject Property to True where list box will be printed when the document is printed

.PrintObject = True

‘List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List (Index)

‘fill ListBox

‘.List = rngSource.Value

‘AddItem Method adds an item to a list box or a combo box — AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.AddItem rngSource(i, 1).Value

Next i

‘alternatively, add item individually, ie. one by one:

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘xlSimple allows multiple selections

.MultiSelect = xlSimple

‘Select multiple items in the ListBox

For i = 1 To .ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.Selected(i) = True

End If

Next i

End With

End Sub

Example: ActiveX Control ListBox & Macro associated with the Click event of the ListBox:

Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b

Sub ActiveXControl_ListBox_OLEobject_Properties_1()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4b

Dim ws As Worksheet, rngListBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objLB As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ListBox

Set rngListBox = Range(«A8»)

‘delete ActiveX Control ListBox objects

For Each objLB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLB.Object) = «ListBox» Then objLB.Delete

Next objLB

‘delete all Form Control ListBox objects in worksheet:

ws.ListBoxes.Delete

Set rngSource = Range(«A2:D7»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range

rngSource.ColumnWidth = 6

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBox.RowHeight = 50

‘ListBox range / cell (rngListBox) resized to add 2 columns

rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True

‘for an already existing ActiveX control listbox, with the name «ListBox1»

‘Set objLB = ws.OLEObjects(«ListBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=20, Height:=20)

With objLB

‘not required for a new listbox
If .ListFillRange = «« Then

‘Clear Method removes all items in a ComboBox or ListBox — it will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.

‘.Object.Clear

‘RemoveItem Method removes a specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index specifies the row number to be removed, wherein the first row is numbered 0.

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

For i = .Object.ListCount — 1 To 0 Step -1

.Object.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource

.ListFillRange = ««

End If

‘set a String value as name for the List Box

.Name = «ListBox1«

‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ListFillRange = rngSource.Address

‘alternatively:

‘.ListFillRange = «$A$2:$D$7«

‘.ListFillRange = Range(«A2:D7»).Address

‘.ListFillRange = «NamedRange«

‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ListBox control — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property

‘LinkedCell is to the right of the ListBox cell

With rngListBox.Offset(0, 1)

.Value = ««

.Interior.Color = vbYellow

.HorizontalAlignment = xlCenter

End With

.linkedCell = rngListBox.Offset(0, 1).Address

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘determines how the control visually appears

‘.SpecialEffect = fmSpecialEffectRaised

‘ColumnHeads Property: A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox.

.ColumnHeads = True

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 4

‘set width of each column — displays only the first column

.ColumnWidths = «70;0;0;0«

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryFirstLetter

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to red

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial«

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘MultiSelect Property: Specifies whether multiple selections are allowed. There are 3 settings: (i) fmMultiSelectSingle (value 0), the default setting, wherein only a single item can be selected; (ii) fmMultiSelectMulti (value 1) which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) fmMultiSelectExtended (value 2) which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection) & this option also allows to select or deselect an item by pressing CTRL and clicking mouse.

.MultiSelect = fmMultiSelectSingle

‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.

.ListIndex = 1

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

‘MsgBox .ListCount

‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).

‘TextColumn property specifies the column of data in a ListBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.

.TextColumn = 1

‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1

‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).

.BoundColumn = 4

‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).

MsgBox .Value

End With

‘size the ListBox with the resized range

‘the Range.Width property returns the width of a column in points

.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width

.Height = rngListBox.Height

‘set shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

‘list box will be printed when the document is printed

.PrintObject = True

.Activate

End With

End Sub

Macro associated with the Click event of the ListBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ListBox1)

Private Sub ListBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ListBox1

On Error Resume Next

Dim cat As String, str As String, rng As Range, BMI As Single

Set rng = Range(«A10»)

rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True

‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2

‘BMI Categories:

‘Underweight = <18.5

‘Normal weight = 18.5–24.9

‘Overweight = 25–29.9

‘Obesity = BMI of 30 or greater

‘assign Value property to BMI

BMI = ListBox1.Object.Value

If BMI < 18.5 Then

cat = «Underweight«

ElseIf BMI < 25 Then

cat = «Normal Weight«

ElseIf BMI < 30 Then

cat = «Overweight«

ElseIf BMI >= 30 Then

cat = «Obese«

End If

With rng

.Interior.Color = vbGreen

.HorizontalAlignment = xlCenter

‘Listbox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Listbox Value Property)

.Value = ListBox1.Object.Text & » is » & cat

End With

End Sub

Example: Add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c

Sub ActiveXControl_ListBox_OLEobject_Properties_2()
‘add a new OLEObject to a sheet — ActiveX control (ListBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 4c

Dim ws As Worksheet, rngListBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objLB As OLEObject, i As Integer

Set ws = Sheets(«Sheet9»)

ws.Activate

‘set range/cell for ListBox

Set rngListBox = Range(«A8»)

‘delete ActiveX Control ListBox objects

For Each objLB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLB.Object) = «ListBox» Then objLB.Delete

Next objLB

‘delete Form Control ListBox objects

Dim sh As Shape

For Each sh In ActiveSheet.Shapes

If sh.Type = msoFormControl Then

If sh.FormControlType = xlListBox Then sh.Delete

End If

Next sh

Set rngSource = Range(«A2:C7»)

‘ListBox range / cell (rngListBox) resized to add 2 columns

rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).MergeCells = True

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range

rngListBox.Resize(1, rngListBox.Columns.Count + 2).ColumnWidth = 9

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngListBox.RowHeight = 40

‘for an already existing ActiveX control listbox, with the name «ListBox1»

‘Set objLB = ws.OLEObjects(«ListBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objLB = ws.OLEObjects.Add(ClassType:=»Forms.ListBox.1«, DisplayAsIcon:=False, Left:=rngListBox.Left, Top:=rngListBox.Top, Width:=100, Height:=20)

With objLB

‘not required for a new listbox

If .ListFillRange = «» Then

‘.Object.Clear

‘deleting row from ListBox using RemoveItem method:

For i = .Object.ListCount — 1 To 0 Step -1

.Object.RemoveItem (i)

Next

Else

‘clear ListBox if filled with ListFillRange/RowSource

.ListFillRange = ««

End If

‘set a String value as name for the List Box

.Name = «ListBox1«

‘remove LinkedCell — you cannot link a worksheet cell for MultiSelect ListBox by using the LinkedCell property

.linkedCell = ««

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘do not display column headings

.ColumnHeads = False

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 3

‘set width of each column

.ColumnWidths = «50;40;40«

‘allow multiple selections in ListBox

.MultiSelect = fmMultiSelectMulti

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryFirstLetter

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to red

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial«

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘AddItem Method adds an item to the list (in a single-column ListBox or ComboBox) & adds a row to the list or an item for each row (in a multi-column ListBox or ComboBox). Syntax: Control.AddItem(Item, Index). Item specifies the item or row to add. Index specifies the position where the new item or row is placed within the list, and if omitted, the item or row is added at the end. The item or row numbers begin with zero, and the first item or row is numbered 0, and so on. The value of Index cannot be greater than the total number of rows (ie. value of ListCount property). AddItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use.

Dim iRow As Integer, iColumn As Integer

For iRow = 1 To rngSource.Rows.Count

‘Create a new row with AddItem

.AddItem rngSource(iRow, 1).Value

For iColumn = 2 To rngSource.Columns.Count

‘add item in columns of each row, using List property

.List(iRow — 1, iColumn — 1) = rngSource(iRow, iColumn).Value

Next iColumn

Next iRow

‘In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection.

‘Select items in the ListBox

For i = 1 To .ListCount

‘select every even item

If i Mod 2 = 0 Then

‘Selected Property specifies whether an item is selected in a ListBox control (not valid for ComboBox). Syntax: Control.Selected(Item_Index).

.Selected(i — 1) = True

End If

Next i

‘copying Selected rows in a multi-column ListBox to corresponding worksheet rows & columns, below the ListBox:

Dim counter As Integer

counter = 0

For i = 0 To .ListCount — 1

If .Selected(i) = True Then

counter = counter + 1

For iColCount = 1 To .ColumnCount

ws.Cells(rngListBox.Row + counter, iColCount).Value = .List(i, iColCount — 1)

‘alternatively, use Column Property instead of List property

‘Column Property refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow).iColumn specifies the column number & iRow specifies the row number wherein both column & row nos start with zero for the first column & row. Specifying both column and row numbers will refer to a specific item, and specifying only the column number will refer to a specific column in the current row viz. ListBox1.Column(1) refers the second column.

‘ws.Cells(rngListBox.Row + counter, iColCount).Value = .Column(iColCount — 1, i)

Next iColCount

End If

Next i

End With

‘size the ListBox with the resized range

‘the Range.Width property returns the width of a column in points

.Width = rngListBox.Resize(rngListBox.Rows.Count, rngListBox.Columns.Count + 2).Width

‘Range.Height Property returns or sets the height of the range, in points

.Height = rngListBox.Height

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

.Activate

End With

End Sub

Example: Form Control Combo Box & Macro to which it is assigned:

Create an Excel Form Control (combo box) & set ComboBox properties — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Refer Image 5a

Sub FormControl_ComboBox_Shape_Properties()
‘create an Excel Form Control (combo box) — use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — refer Image 5a
‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.
‘Form Control ComboBox allows a single column, use an ActiveX ComboBox for multi columns
‘use an ActiveX ComboBox to enable the user to edit the text in the text box — Form Control ComboBox does not allow this

Dim shpComboBx As Shape, ws As Worksheet, rngComboBx As Range, rngSource As Range, objComboBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ComboBox

Set rngComboBx = ws.Range(«B10»)

‘delete ActiveX Control ComboBox objects

For Each objComboBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objComboBx.Object) = «ComboBox» Then objComboBx.Delete

Next objComboBx

‘delete Form Control ComboBox objects

For Each shpComboBx In ActiveSheet.Shapes

If shpComboBx.Type = msoFormControl Then

If shpComboBx.FormControlType = xlDropDown Then shpComboBx.Delete

End If

Next shpComboBx

Set rngSource = Range(«B2:F2»)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngComboBx.ColumnWidth = 11

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngComboBx.RowHeight = 17

‘for an already existing Form Control shape — ComboBox, with the name «Combo Box 1»

‘Set shpComboBx = ws.Shapes(«Combo Box 1»)

‘set object variable to the newly added ComboBox Form control — position & size the ComboBox with the cell assigned to the rngComboBx variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpComboBx = ws.Shapes.AddFormControl(xlDropDown, Left:=rngComboBx.Left, Top:=rngComboBx.Top, Width:=rngComboBx.Width, Height:=rngComboBx.Height)

‘remove all items from ComboBox:

With shpComboBx

‘remove all items if List Method has been used to set the text entries in the specified list box as an array of strings, or if the AddItem Method has been used to add items to a list box

If .ControlFormat.ListFillRange = «« Then

‘ControlFormat.RemoveAllItems Method removes all entries from a Microsoft Excel list box or combo box.

‘.ControlFormat.RemoveAllItems

‘ControlFormat.ListCount Property determines the total number of items in a ListBox or ComboBox.

For i = .ControlFormat.ListCount To 1 Step -1

‘ControlFormat.RemoveItem Method removes one or more items from a list box or combo box — ControlFormat.RemoveItem(Index, Count) — Index is the number of the first item to be removed, having values from 1 to the number of items in the list — this method will fail if the list box has a defined fill range.

.ControlFormat.RemoveItem (i)

Next

Else

‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

.ControlFormat.ListFillRange = ««

End If

‘set a String value as object’s name

.Name = «Combo Box 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

.AlternativeText = «ComBx«

‘turn 3D Shading Off

.OLEFormat.Object.Display3DShading = True

‘enable the object

.ControlFormat.Enabled = True

‘set ControlFormat.PrintObject Property to True where list box will be printed when the document is printed

.ControlFormat.PrintObject = True

‘ControlFormat.ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

.ControlFormat.ListFillRange = rngSource.Address

‘alternatively:

‘.ControlFormat.ListFillRange = «$B$2:$F$2»

‘.ControlFormat.ListFillRange = Range(«B2:F2»).Address

‘.ControlFormat.ListFillRange = «NamedRange»

‘———————

‘ControlFormat.List Method returns or sets the text entries in the specified list box or a combo box, as an array of strings, or returns or sets a single text entry. An error occurs if there are no entries in the list — ControlFormat.List(Index)

‘fill ComboBox

‘.OLEFormat.Object.List = rngSource.Value

‘.OLEFormat.Object.List = Range(«B2:F2»).Value

‘replace value of the second item in the list, using the ControlFormat.List Method:

‘.OLEFormat.Object.List(2) = «ChangeItem»

‘.OLEFormat.Object.List = Array(«2010», «2011», «2012», «2013»)

‘return first item:

MsgBox .ControlFormat.List(1)

‘alternatively — return first item:

MsgBox .OLEFormat.Object.List(1)

‘ControlFormat.DropDownLines Property returns or sets the number of list lines displayed in the drop-down portion of a combo box. ControlFormat.DropDownLines

.ControlFormat.DropDownLines = 3

‘ControlFormat.AddItem Method adds an item to a list box or a combo box — ControlFormat.AddItem(Text, Index) — using this method clears any range specified by the ListFillRange property.

For i = 1 To rngSource.Columns.Count

‘Create a new row with AddItem

.ControlFormat.AddItem rngSource(1, i).Value

Next i

‘alternatively:

‘With .ControlFormat

‘.AddItem «2010»

‘.AddItem «2011»

‘.AddItem «2012»

‘.AddItem «2013»

‘End With

‘ControlFormat.ListIndex Property returns or sets the index number of the currently selected item in a ComboBox or ListBox. This property cannot be used with multiselect list boxes.

‘ComboBox displays the current value in the text box, regardless of how that value is entered

.ControlFormat.ListIndex = 1

‘return selected item from ComboBox

MsgBox .ControlFormat.List(.ControlFormat.ListIndex)

‘ControlFormat.ListCount Property returns the total number of entries in a ListBox or ComboBox, & returns 0 (zero) for no entries in the list

MsgBox .ControlFormat.ListCount

‘Value Property: For the Form Controls ComboBox & ListBox (value cannot be used with a multi-select ListBox), value is the the index number of the currently selected item (ie. ControlFormat.ListIndex)

MsgBox .ControlFormat.Value

‘use the ControlFormat.LinkedCell property (not valid for a multi-select ComboBox), to set the worksheet range linked to the index number of the currently selected item in a ComboBox or ListBox (ie. ControlFormat.ListIndex)

‘enter the selection’s list position to a specific cell — the linked cell returns the number of the selected item in the drop-down list of the combo box.

.ControlFormat.linkedCell = rngComboBx.Address

‘to return the actual item from the input range, enter the index formula in the separate cell wherein you wish to get the actual item

‘rngComboBx.Offset(-1, 0).Value = Application.WorksheetFunction.Index(rngSource, rngComboBx.Value)

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro

.OnAction = «ComboBoxClick«

End With

‘————————————-

‘copy combo box and create new combo box with same properties

‘set range size, for cell below the existing combo box

rngComboBx.Offset(1, 0).ColumnWidth = rngComboBx.ColumnWidth

rngComboBx.Offset(1, 0).RowHeight = rngComboBx.Height

‘copy combo box to clipboard

ws.Shapes(«Combo Box 1»).Copy

‘paste a copy of the combobox in the same sheet

ws.Paste

‘fit new combo box in the cell below the existing check box

Selection.Left = rngComboBx.Offset(1, 0).Left

Selection.Top = rngComboBx.Offset(1, 0).Top

Selection.Name = «Combo Box 2«

Selection.linkedCell = rngComboBx.Offset(1, 0).Address

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ComboBoxClick macro

Selection.OnAction = «ComboBoxClick«

Dim rngSource2 As Range

Set rngSource2 = Range(«A3:A7»)

ws.Shapes(«Combo Box 2»).OLEFormat.Object.List = rngSource2.Value

‘————————————-

‘call the ComboBoxClick macro

Call ComboBoxClick

End Sub

Macro to which the Form Control ComboBox is assigned — this procedure is located in a standard module of the workbook & executes on clicking / changing «Combo Box 1» or «Combo Box 2» value

Sub ComboBoxClick()
‘this macro has been assigned to «Combo Box 1» & «Combo Box 2», & will execute when combobox selection changes

Dim shpComboBx1 As Shape, shpComboBx2 As Shape, ws As Worksheet, rngSource As Range, rngResult As Range, c As Integer, r As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rngSource = Range(«B3:F7»)

Set rngResult = Range(«B13»)

‘set object variable to an existing Form Control shape — ComboBox

Set shpComboBx1 = ws.Shapes(«Combo Box 1»)

Set shpComboBx2 = ws.Shapes(«Combo Box 2»)

‘column number in range given by combo box 1

c = shpComboBx1.ControlFormat.Value

‘row number in range given by combo box 2

r = shpComboBx2.ControlFormat.Value

rngResult.Value = Application.WorksheetFunction.Index(rngSource, r, c)

rngResult.Interior.Color = RGB(0, 255, 0)

rngResult.NumberFormat = «$#,##0«

End Sub

Example: ActiveX Control ComboBox & Macro associated with the Click event of the ComboBox:

Add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b

Sub ActiveXControl_ComboBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ComboBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 5b

Dim ws As Worksheet, rngComboBox As Range, rngSource As Range

‘OLEObject is not used for Form Controls

Dim objCoBx As OLEObject, i As Integer

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ComboBox

Set rngComboBox = Range(«A8»)

‘delete ActiveX Control ComboBox objects

For Each objCoBx In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objCoBx.Object) = «ComboBox» Then objCoBx.Delete

Next objCoBx

‘delete all Form Control ComboBox objects in worksheet:

ws.DropDowns.Delete

Set rngSource = Range(«A2:D7»)

‘ListBox range / cell (rngComboBox) resized to add 2 columns

rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).MergeCells = True

‘Range.ColumnWidth Property sets the width of all columns in the specified range

rngComboBox.Resize(1, rngComboBox.Columns.Count + 3).ColumnWidth = 7

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngComboBox.RowHeight = 18

‘for an already existing ActiveX control ComboBox, with the name «ComboBox1»

‘Set objCoBx = ws.OLEObjects(«ComboBox1»)

‘set object variable to the newly added listbox ActiveX control

Set objCoBx = ws.OLEObjects.Add(ClassType:=»Forms.ComboBox.1«, DisplayAsIcon:=False, Left:=rngComboBox.Left, Top:=rngComboBox.Top, Width:=40, Height:=20)

With objCoBx

‘set a String value as name for the List Box

.Name = «ComboBox1«

‘LinkedCell property sets the worksheet range linked to the control’s value so that the linked cell displays the selected value from the ComboBox control

‘LinkedCell is 1 column to the right of the ComboBox cell

With rngComboBox.Offset(0, 1)

.NumberFormat = «#,##0.0«

.Value = ««

.Interior.Color = vbYellow

.HorizontalAlignment = xlCenter

End With

.linkedCell = rngComboBox.Offset(0, 1).Address

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘display column headings (if combobox is filled with ListFillRange/RowSource)

.ColumnHeads = True

‘ColumnCount Property specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns.

.ColumnCount = 3

‘set width of each column

.ColumnWidths = «50;40;40«

‘fmShowDropButtonWhenAlways — always shows the drop-down button; fmShowDropButtonWhenNever — never shows the drop-down button; fmShowDropButtonWhenFocus — shows the drop-down button only when the control has focus.

.ShowDropButtonWhen = fmShowDropButtonWhenAlways

‘Style Property determines choosing or setting the value of ComboBox (not valid for ListBox). There are 2 settings: (i) fmStyleDropDownCombo (value 0 — default) — user has both options of typing a custom value in the text area or select from the drop-down list; (ii) fmStyleDropDownList (value 2) — user can only select from the drop-down list, like in ListBox.

.Style = fmStyleDropDownCombo

‘enabling the DragBehavior property enables the drag-and-drop feature for ComboBox — dragging in combo box starts a drag-and-drop operation on the selected text but not in the drop-down portion — DragBehavior has no effect on a ComboBox whose Style property is set to fmStyleDropDownList

.DragBehavior = fmDragBehaviorEnabled

.BorderStyle = fmBorderStyleSingle

.BorderColor = RGB(255, 0, 0)

.MatchEntry = fmMatchEntryComplete

.ListStyle = fmListStyleOption

‘set background color

.BackColor = RGB(216, 216, 216)

‘set font color to blue

.ForeColor = RGB(0, 0, 255)

With .Font

.Name = «Arial»

.Bold = False

.Size = 9

.Italic = False

.Underline = False

End With

‘Populate ComboBox from an Array:

‘create a 2-dimensional array and load to ComboBox using the List property (copies an array without transposing it)

Dim myArray(5, 3)

‘Declaring the array and its dimensions. The array has been named myArray, of size 5 by 3 (5 rows by 3 columns). Note: When you populate an array with data, the array will start at zero, and if you include Option Base 1 the array will start at 1.

‘populate rows & columns of myArray, with worksheet range (rngSource)

For c = 0 To 2

For r = 0 To 5

myArray(r, c) = rngSource(r + 1, c + 1)

Next r

Next c

‘copy data to ComboBox using List property — copies an array without transposing it:

.List() = myArray

‘remove all items if ListFillRange has not been used to fill the combo box

If objCoBx.ListFillRange = «« Then

‘.Clear

‘deleting row from ListBox using RemoveItem method:

For i = .ListCount — 1 To 0 Step -1

.RemoveItem (i)

Next

Else

‘clear ComboBox if filled with ListFillRange/RowSource (if ListFillRange property has been used to specify the source of a list)

objCoBx.ListFillRange = ««

End If

‘ListFillRange property specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox.

objCoBx.ListFillRange = rngSource.Address

‘alternatively:

‘objCoBx.ListFillRange = «$A$2:$C$7«

‘objCoBx.ListFillRange = Range(«A2:C7»).Address

‘objCoBx.ListFillRange = «NamedRange«

‘TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property).

‘TextColumn property specifies the column of data in a ComboBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value if the TextColumn property is not set. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. Setting the TextColumn value to 0 returns the ListIndex value (the number of the selected row) in Text Property — this setting is useful if you want to determine the row of the selected item.

.TextColumn = 1

‘BoundColumn Property: Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1

‘Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox).

.BoundColumn = 4

‘ListIndex Property determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on.

.ListIndex = 2

‘Value Property: For the controls ComboBox and ListBox (value cannot be used with a multi-select ListBox), it is the value in the BoundColumn of the currently selected row (BoundColumn property specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user).

MsgBox .Value

‘Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox

‘ListCount Property determines the total number of rows in a ListBox or ComboBox.

If .ListCount > 5 Then

‘ListRows Property specifies the maximum number of rows which will display in the list box portion of a ComboBox. The default value is 8. Note: If the actual number of list items exceed this maximum value of the ListRows property, a vertical scroll bar will appear in the list box portion of the ComboBox (and the excess list items can be viewed by scrolling down).

.ListRows = 4

Else

.ListRows = .ListCount

End If

End With

‘size the ComboBox with the resized range

‘set column width in points

.Width = rngComboBox.Resize(rngComboBox.Rows.Count, rngComboBox.Columns.Count + 3).Width

‘Range.Height Property returns or sets the height of the range, in points

.Height = rngComboBox.Height

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘enable the object

.Enabled = True

.Activate

End With

End Sub

Macro associated with the Click event of the ComboBox1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ComboBox1) — refer Image 5c

Private Sub ComboBox1_Click()
‘on clicking / selecting an item in the ActiveX Control ComboBox1 — refer Image 5c

On Error Resume Next

Dim cat As String, str As String, rng As Range, BMI As Single

Set rng = Range(«A10»)

rng.Resize(rng.Rows.Count, rng.Columns.Count + 2).MergeCells = True

‘Body Mass Index formula is — weight in kilograms divided by the square of height in meters: kg/m2

‘BMI Categories:

‘Underweight = <18.5

‘Normal weight = 18.5–24.9

‘Overweight = 25–29.9

‘Obesity = BMI of 30 or greater

‘assign Value property to BMI

BMI = ComboBox1.Object.Value

If BMI < 18.5 Then

cat = «Underweight»

ElseIf BMI < 25 Then

cat = «Normal Weight»

ElseIf BMI < 30 Then

cat = «Overweight»

ElseIf BMI >= 30 Then

cat = «Obese»

End If

With rng

.Interior.Color = vbGreen

.HorizontalAlignment = xlCenter

‘Combobox Text Property gives the Name, & BMI Category (cat) is derived from BMI (Combobox Value Property)

.Value = ComboBox1.Object.Text & » is » & cat

End With

End Sub

Option Button — Form Control or ActiveX Control

OptionButton is used to make one selection from multiple options. It is also referred to as a Radio Button, which chooses one option from a group of mutually exclusive options. If OptionButtons are not grouped, selecting one OptionButton will de-select all other OptionButtons. All OptionsButtons within a specific Group become mutually exclusive and self-contained within that group and do not affect selection of OptionButtons outside that group. Selecting an OptionButton in one group will de-select all other OptionButtons of only that group. The Value property of an OptionButton indicates whether it is selected or not. A True value indicates that the OptionButton is selected, False is the default value and indicates that it is not selected.

CheckBox vs OptionButton: With CheckBox, user can select multiple options, by selecting each CheckBox against which an option is available. OptionButton is used when user is allowed to select only a single option. CheckBox can be used in a singular manner viz. a single CheckBox can be selected or deselected (by clicking itself) indicating whether an option is to be exercised or not. OptionButton on the other hand are used in multiples viz. two or more, to indicate selection of mutually exculsive options. OptionButton gets deselected only on selection of another OptionButton and not by clicking itself.

Below we illustrate, a Form Control OptionButton, and an ActiveX Control OptionButton.

Example: Form Control Option Button:

Use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a

Sub FormControl_OptionButton_GroupBox_Shape_Properties()
‘use Shapes.AddFormControl Method to create Excel Form Controls (Option Button & Group Box) — this returns a Shape object representing the new control — refer Image 6a

Dim shpOptnBtn As Shape, ws As Worksheet, rngOptnBtn As Range, objOptnBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rngOptnBtn = Range(«B2»)

‘delete ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete

Next objOptnBtn

‘delete all (Form Control) Option Buttons in worksheet

ws.OptionButtons.Delete

‘delete all (Form Control) group boxes in worksheet

ws.GroupBoxes.Delete

rngOptnBtn.ColumnWidth = 11

rngOptnBtn.RowHeight = 17

‘for an already existing Form Control shape — Option Button, with the name «Option Button 1»

‘Set shpOptnBtn = ws.Shapes(«Option Button 1»)

‘set object variable to the newly added Option Button Form control — position & size the Option Button with the cell assigned to the rngOptnBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpOptnBtn = ws.Shapes.AddFormControl(xlOptionButton, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)

With shpOptnBtn

‘set a String value as object’s name

.Name = «Option Button 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button

.TopLeftCell.Offset(0, -1) = «Country«

‘specify caption text

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Click to Select«

‘use the .OLEFormat.Object object to manipulate Display3DShading

.OLEFormat.Object.Display3DShading = False

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘OptionButton will be printed when the document is printed

.PrintObject = True

End With

‘set check box fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘set background color to yellow

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border for OptionButton

With .Line

.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

.Visible = msoTrue

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(255, 0, 0)

End With

End With

‘————————————-

‘create second option button (by copying the first)

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height

‘copy check box to clipboard

ws.Shapes(«Option Button 1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(1, 0).Left

Selection.Top = rngOptnBtn.Offset(1, 0).Top

Selection.Name = «Option Button 2«

Selection.Characters.Text = «Canada«

‘alternatively

‘Selection.Caption = «Canada«

‘merge & format cells to the left of OptionButtons 1 & 2

Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘create third & fourth option buttons (by copying the first)

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.Shapes(«Option Button 1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(3, 0).Left

Selection.Top = rngOptnBtn.Offset(3, 0).Top

Selection.Name = «Option Button 3«

Selection.Caption = «Spain«

‘wrt to the cell which is under the upper-left corner of the Option Button — enter text in the same row to the left of the Option Button

Selection.TopLeftCell.Offset(0, -1) = «Country«

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton3 to clipboard

ws.Shapes(«Option Button 3»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(4, 0).Left

Selection.Top = rngOptnBtn.Offset(4, 0).Top

Selection.Name = «Option Button 4«

Selection.Caption = «France«

‘merge & format cells to the left of OptionButtons 3 & 4

Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘create 2 (Form Control) group boxes, to include 2 option buttons each

Dim rngGB1 As Range, rngGB2 As Range

‘resize the range for group box to include the range of first & second option buttons

Set rngGB1 = rngOptnBtn.Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)

‘resize the range for group box to include the the range of third & fourth option buttons

Set rngGB2 = rngOptnBtn.Offset(3, 0).Resize(rngOptnBtn.Rows.Count + 1, rngOptnBtn.Columns.Count)

‘add first Group Box — position & size the group box to include the option buttons 1 & 2

With ws.GroupBoxes.Add(Left:=rngGB1.Left, Top:=rngGB1.Top, Width:=rngGB1.Width, Height:=rngGB1.Height)

‘set group box name

.Name = «America«

‘do not display caption

.Characters.Text = ««

.Placement = xlFreeFloating

End With

‘add second Group Box — position & size the group box to include the option buttons 3 & 4

With ws.GroupBoxes.Add(Left:=rngGB2.Left, Top:=rngGB2.Top, Width:=rngGB2.Width, Height:=rngGB2.Height)

.Name = «Europe«

.Characters.Text = ««

.Placement = xlFreeFloating

End With

‘enter in the cell to the left of option buttons 1 & 3

ws.Shapes(«Option Button 1»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(1).Name

ws.Shapes(«Option Button 3»).TopLeftCell.Offset(0, -1).Value = ws.GroupBoxes(2).Name

‘you may use the same linked cell for all option buttons within a group, because the linked cell returns the number of the selected option button within in the group viz. the first option button within a group returns 1, the second option button returns 2, and so on. For multiple groups on a worksheet, use a different linked cell for each group of option buttons.

ws.Shapes(«Option Button 1»).ControlFormat.linkedCell = rngOptnBtn.Address

ws.Shapes(«Option Button 2»).ControlFormat.linkedCell = rngOptnBtn.Address

ws.Shapes(«Option Button 3»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address

ws.Shapes(«Option Button 4»).ControlFormat.linkedCell = rngOptnBtn.Offset(3, 0).Address

‘Value property of a OptionButton indicates whether it is selected or not.

‘select option buttons 1 & 4

ws.Shapes(«Option Button 1»).ControlFormat.Value = xlOn

ws.Shapes(«Option Button 4»).ControlFormat.Value = xlOn

Dim str As String

‘————————————

‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 1:

‘Form Control OptionButton objects

‘For Each shpOptnBtn In ActiveSheet.Shapes

‘If shpOptnBtn.FormControlType = xlOptionButton Then

‘if option button is 1 or 2, & if selected

‘If (shpOptnBtn.Name = «Option Button 1» Or shpOptnBtn.Name = «Option Button 2») And shpOptnBtn.ControlFormat.Value = xlOn Then

‘return the selected OptionButton’s caption & its GroupBox’ name

‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name

‘End If

‘if option button is 3 or 4, & if selected

‘If (shpOptnBtn.Name = «Option Button 3» Or shpOptnBtn.Name = «Option Button 4») And shpOptnBtn.ControlFormat.Value = xlOn Then

‘return the selected OptionButton’s caption & its GroupBox’ name

‘str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name

‘End If

‘End If

‘Next

‘————————————

‘return the selected OptionButton’s caption & its GroupBox’ name — alternate 2:

‘Form Control OptionButton objects

For Each shpOptnBtn In ActiveSheet.Shapes

If shpOptnBtn.FormControlType = xlOptionButton Then

‘if option button range intersects with group box 1 range (ie. if option button is 1 or 2), & if selected

If Not Intersect(shpOptnBtn.TopLeftCell, rngGB1) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then

‘return the selected OptionButton’s caption & its GroupBox’ name

str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(1).Name

End If

‘if option button range intersects with group box 2 range (ie. if option button is 3 or 4), & if selected

If Not Intersect(shpOptnBtn.TopLeftCell, rngGB2) Is Nothing And shpOptnBtn.ControlFormat.Value = 1 Then

‘return the selected OptionButton’s caption & its GroupBox’ name

str = str & «; » & shpOptnBtn.TextFrame.Characters.Text & » in » & ws.GroupBoxes(2).Name

End If

End If

Next

‘delete starting «;»

‘return the caption & group name of Selected option buttons

If Left(str, 1) = «;» Then

‘returns: «USA in America; France in Europe»

str = Right(str, Len(str) — 2)

MsgBox str

Else

MsgBox str

End If

End Sub

Example: ActiveX Control Option Button:

Add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object, set GroupName for Option Buttons — refer Image 6b

Sub ActiveXControl_OptionButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (OptionButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 6b
‘set a group name — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group

Dim ws As Worksheet, rngOptnBtn As Range

‘OLEObject is not used for Form Controls

Dim objOptnBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for OptionButton

Set rngOptnBtn = Range(«B2»)

‘delete ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then objOptnBtn.Delete

Next objOptnBtn

‘delete Form Control OptionButton objects

Dim sh As Shape

For Each sh In ActiveSheet.Shapes

If sh.Type = msoFormControl Then

If sh.FormControlType = xlOptionButton Then sh.Delete

End If

Next sh

‘delete all (Form Control) group boxes in worksheet

ws.GroupBoxes.Delete

rngOptnBtn.ColumnWidth = 11

rngOptnBtn.RowHeight = 17

‘for an already existing ActiveX control OptionButton, with the name «OptionButton1»

‘Set objOptnBtn = ws.OLEObjects(«OptionButton1»)

‘set object variable to the newly added OptionButton ActiveX control — position & size the OptionButton with the cell assigned to the rngOptnBtn variable

Set objOptnBtn = ws.OLEObjects.Add(ClassType:=»Forms.OptionButton.1«, DisplayAsIcon:=False, Left:=rngOptnBtn.Left, Top:=rngOptnBtn.Top, Width:=rngOptnBtn.Width, Height:=rngOptnBtn.Height)

With objOptnBtn

‘set a String value as object’s name

.Name = «OptionButton1«

‘returns the index number of the object within the collection of similar objects

‘MsgBox .Index

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘OptionButton will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘.LinkedCell = «Sheet1!B2«

.linkedCell = rngOptnBtn.Address

‘wrt to the cell which is under the upper-left corner of the option button — enter text in the same row to the left of the option button

.TopLeftCell.Offset(0, -1) = «Country«

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘TripleState property if set to True, will enable OptionButton to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a OptionButton indicates whether it is selected or not. True (integer value 1) indicates that the OptionButton is selected, False (value of 0) indicates that it is cleared; and the Null value indicates that it is neither selected nor cleared, and the OptionButton will appear shaded in this case. The value of TripleState property should be set to True for the OptionButton to have a Null value.

.Value = False

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify how caption will appear relative to the control

.Alignment = fmAlignmentLeft

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture to be displayed on the ActiveX control

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «USA«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial»

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

‘———————-

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(1, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(1, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.OLEObjects(«OptionButton1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(1, 0).Left

Selection.Top = rngOptnBtn.Offset(1, 0).Top

Selection.Name = «OptionButton2«

ws.OLEObjects(«OptionButton2»).linkedCell = rngOptnBtn.Offset(1, 0).Address

ws.OLEObjects(«OptionButton2»).Object.Caption = «Canada«

‘merge & format cells to the left of both OptionButtons

Union(rngOptnBtn.Offset(0, -1), rngOptnBtn.Offset(1, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(3, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(3, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton1 to clipboard

ws.OLEObjects(«OptionButton1»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(3, 0).Left

Selection.Top = rngOptnBtn.Offset(3, 0).Top

Selection.Name = «OptionButton3»

ws.OLEObjects(«OptionButton3»).linkedCell = rngOptnBtn.Offset(3, 0).Address

ws.OLEObjects(«OptionButton3»).Object.Caption = «Spain«

‘wrt to the cell which is under the upper-left corner of the option button

ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Country«

‘copy OptionButton and create new OptionButton with same properties

‘set range size, for cell below the existing OptionButton

rngOptnBtn.Offset(4, 0).ColumnWidth = rngOptnBtn.ColumnWidth

rngOptnBtn.Offset(4, 0).RowHeight = rngOptnBtn.Height

‘copy OptionButton3 to clipboard

ws.OLEObjects(«OptionButton3»).Copy

‘paste a copy of the OptionButton in the same sheet

ws.Paste

‘fit new OptionButton in the cell below the existing OptionButton

Selection.Left = rngOptnBtn.Offset(4, 0).Left

Selection.Top = rngOptnBtn.Offset(4, 0).Top

Selection.Name = «OptionButton4»

ws.OLEObjects(«OptionButton4»).linkedCell = rngOptnBtn.Offset(4, 0).Address

ws.OLEObjects(«OptionButton4»).Object.Caption = «France»

‘merge & format cells to the left of OptionButtons 3 & 4

Union(rngOptnBtn.Offset(3, -1), rngOptnBtn.Offset(4, -1)).Select

With Selection

.HorizontalAlignment = xlCenter

.VerticalAlignment = xlCenter

.ReadingOrder = xlContext

.MergeCells = True

.Interior.Color = RGB(0, 255, 0)

End With

‘———————-

‘use the GroupName property to set a group name for an option button — OptionButtons having the same GroupName become mutually exclusive and selecting one OptionButton will de-select all other OptionButtons of that group

ws.OLEObjects(«OptionButton1»).Object.GroupName = «America«

ws.OLEObjects(«OptionButton2»).Object.GroupName = «America«

ws.OLEObjects(«OptionButton3»).Object.GroupName = «Europe«

ws.OLEObjects(«OptionButton4»).Object.GroupName = «Europe«

‘enter group names on the left of option buttons

ws.OLEObjects(«OptionButton1»).TopLeftCell.Offset(0, -1) = «America«

ws.OLEObjects(«OptionButton3»).TopLeftCell.Offset(0, -1) = «Europe«

‘select option buttons 2 & 4

ws.OLEObjects(«OptionButton2»).Object = True

ws.OLEObjects(«OptionButton4»).Object = True

Dim str As String

‘ActiveX Control OptionButton objects

For Each objOptnBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objOptnBtn.Object) = «OptionButton» Then

If objOptnBtn.Object.GroupName = «America» And objOptnBtn.Object.Value = True Then

str = str & «; » & objOptnBtn.Object.Caption & » in America»

End If

If objOptnBtn.Object.GroupName = «Europe» And objOptnBtn.Object.Value = True Then

str = str & «; » & objOptnBtn.Object.Caption & » in Europe»

End If

End If

Next

‘delete starting «;»

‘return the caption & group name of Selected option buttons

If Left(str, 1) = «;» Then

‘returns: «USA in America; France in Europe»

str = Right(str, Len(str) — 2)

rngOptnBtn.Offset(6, -1).Value = str

Else

rngOptnBtn.Offset(6, -1).Value = str

End If

End Sub

Toggle Button — ActiveX Control

ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.

Below we illustrate an ActiveX Control ToggleButton a Macro associated with the Click event of this ToggleButton.

Example: ActiveX Control Toggle Button:

Add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a

Sub ActiveXControl_ToggleButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ToggleButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 7a

Dim ws As Worksheet, rngTglBtn As Range

‘OLEObject is not used for Form Controls

Dim objTglBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ToggleButton

Set rngTglBtn = Range(«B2»)

‘delete ActiveX Control ToggleButton objects

For Each objTglBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objTglBtn.Object) = «ToggleButton» Then objTglBtn.Delete

Next objTglBtn

rngTglBtn.ColumnWidth = 22

rngTglBtn.RowHeight = 24

‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»

‘Set objTglBtn = ws.OLEObjects(«ToggleButton1»)

‘set object variable to the newly added ToggleButton ActiveX control — position & size the ToggleButton with the cell assigned to the rngTglBtn variable

Set objTglBtn = ws.OLEObjects.Add(ClassType:=»Forms.ToggleButton.1«, DisplayAsIcon:=False, Left:=rngTglBtn.Left, Top:=rngTglBtn.Top, Width:=rngTglBtn.Width, Height:=rngTglBtn.Height)

With objTglBtn

‘set a String value as object’s name

.Name = «ToggleButton1«

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘toggle buttonwill be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘TopLeftCell — wrt to the cell which is under the upper-left corner of the toggle button

.linkedCell = .TopLeftCell.Offset(0, -1).Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

.TextAlign = fmTextAlignCenter

‘TripleState property if set to True, will enable ToggleButton to have three possible values, including the Null value, besides True & False

.TripleState = False

‘Value property of a ToggleButton indicates whether it is selected or not. True (integer value 1) indicates that the ToggleButton is selected & where it appears as pressed, False (value of 0) indicates that it is unselected where it appears as unpressed; and the Null value indicates that it is neither selected nor cleared, and the ToggleButton will appear shaded in this case. The value of TripleState property should be set to True for the ToggleButton to have a Null value.

.Value = False

‘Accelerator Property sets the key to access a control

.Accelerator = «h«

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘load a picture into ActiveX control, using the LoadPicture Function — specify filename & address of image to be loaded

.Picture = LoadPicture(«C:UsersamitDocumentsPhotosDollar.jpg»)

‘alignment of the picture with its caption

.PicturePosition = fmPicturePositionAboveCenter

‘remove picture

.Picture = LoadPicture(«»)

‘specify caption text

.Caption = «Sort Data«

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to black

.ForeColor = RGB(0, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = True

.Underline = False

End With

End With

End With

End Sub

Macro associated with the Click event of the ToggleButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ToggleButton1) — refer Image 7b

Private Sub ToggleButton1_Click()
‘ToggleButton control generates a Click event for which an event-handler sub procedure has been written here — refer Image 7b
‘ToggleButton is a control which executes one action when clicked first and a different action on the second click. It has two states, On & Off, wherein the button alternates (or toggles) between the two. It can have a value of True (where it appears as pressed) when the button is selected or the value False (appears unpressed) when unselected.

Dim lTotalRows As Long, ws As Worksheet

‘determine total rows in column D:

lTotalRows = Cells(Rows.Count, «D»).End(xlUp).Row

‘if ToggleButton value is True: it appears pressed — data in column D appears sorted in Descending order — button appears in green BackColor and displays the alternate sort option («Get Ascending Order»):

If ToggleButton1.Value = True Then

ToggleButton1.Caption = «Get Ascending Order«

ToggleButton1.BackColor = RGB(0, 255, 0)

Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlDescending

‘if ToggleButton value is False: it appears unpressed — data in column D appears sorted in Ascending order — button appears in red BackColor and displays the alternate sort option («Get Decending Order»):

ElseIf ToggleButton1.Value = False Then

ToggleButton1.Caption = «Get Decending Order«

ToggleButton1.BackColor = RGB(255, 0, 0)

Range(«D2:D» & lTotalRows).Sort key1:=Range(«D2»), order1:=xlAscending

End If

End Sub

ScrollBar & SpinButton Controls — Form Control or ActiveX Control

A ScrollBar control enables to scroll through a range of values when a user: (i) clicks on the scroll arrows; (ii) drags the scroll box; or (iii) clicks in an area between a scroll arrow and the scroll box. Both ScrollBar control & SpinButton control enable to change (increment or decrement) value in a worksheet range. SpinButton control (also referred to as a Spinner control) functions like a ScrollBar control, with similar properties (viz. SmallChange, Min, Max, Orientation, …). Difference between the ScrollBar & SpinButton controls is that the ScrollBar box can be dragged to change the control’s value over larger increments (while keeping the increment low for clicks) which advantages a ScrollBar to make a selection from across a large number of values and cover an extremely wide range. SpinButton control does not have a LargeChange property, like in a ScrollBar, which specifies the incremental change when the user clicks between a scroll arrow and the scroll box.

Below we illustrate: (i) a Form Control Scroll Bar & and assign it to a Macro; and (ii) an ActiveX Control ScrollBar & Macro associated with the Change event of this ScrollBar.

Example: Form Control Scroll Bar & Macro to which it is assigned:

Create an Excel Form Control (Scroll Bar) & set ScrollBar properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 8a

Sub FormControl_ScrollBar_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (ScrollBar) — this returns a Shape object representing the new control — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, shpScrlBar As Shape, objScrlBar As OLEObject

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ScrollBar

Set rngScrlBar1 = Range(«C2»)

Set rngScrlBar2 = Range(«C3»)

Set rngScrlBar3 = Range(«C4»)

‘format cells

With rngScrlBar1.Offset(0, -1).Resize(1, 2)

.Value = ««

.NumberFormat = «$#,##0«

End With

With rngScrlBar2.Offset(0, -1).Resize(2, 2)

.Value = ««

.NumberFormat = «0.0«

End With

With rngScrlBar3.Offset(1, -1)

.Value = «»

.NumberFormat = «$#,##0«

End With

‘delete ActiveX Control ScrollBar objects

For Each objScrlBar In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete

Next objScrlBar

‘delete Form Control ScrollBar objects

For Each shpScrlBar In ActiveSheet.Shapes

If shpScrlBar.Type = msoFormControl Then

If shpScrlBar.FormControlType = xlScrollBar Then shpScrlBar.Delete

End If

Next shpScrlBar

rngScrlBar1.ColumnWidth = 15

rngScrlBar1.RowHeight = 15

‘for an already existing Form Control shape — ScrollBar, with the name «Scroll Bar 1»

‘Set shpScrlBar = ws.Shapes(«Scroll Bar 1»)

‘set object variable to the newly added check box Form control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX scroll bar has an Orientation property which can be set to be Auto, Horizontal, or Vertical

Set shpScrlBar = ws.Shapes.AddFormControl(xlScrollBar, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)

With shpScrlBar

‘set a String value as object’s name

.Name = «Scroll Bar 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Scroll«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

.OnAction = «ScrollBar_CalcPMT«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘scroll bar will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the scroll box — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngScrlBar1.Address

‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting), value of the Max property must be greater than the value of the Min property

.Min = 0

.Max = 10000

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 5

‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.

.LargeChange = 100

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 1000

End With

End With

‘———————-

‘2nd ScrollBar: copy ScrollBar and create second ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar2.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.Shapes(«Scroll Bar 1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar2.Left

Selection.Top = rngScrlBar2.Top

Selection.Name = «Scroll Bar 2«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

Selection.OnAction = «ScrollBar_CalcPMT«

With ws.Shapes(«Scroll Bar 2»).ControlFormat

.linkedCell = rngScrlBar2.Address

.Min = 0

.Max = 500

.SmallChange = 1

.LargeChange = 10

.Value = 50

End With

‘———————-

‘3rd ScrollBar: copy ScrollBar and create third ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar3.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.Shapes(«Scroll Bar 1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar3.Left

Selection.Top = rngScrlBar3.Top

Selection.Name = «Scroll Bar 3«

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on the shape will execute the ScrollBar_CalcPMT macro

Selection.OnAction = «ScrollBar_CalcPMT«

With ws.Shapes(«Scroll Bar 3»).ControlFormat

.linkedCell = rngScrlBar3.Address

.Min = 0

.Max = 60
.SmallChange = 1

.LargeChange = 4

.Value = 20

End With

‘calculate monthly instalment in cell B5, by calling the macro ScrollBar_CalcPMT:

Call ScrollBar_CalcPMT

End Sub

This macro ( located in a standard module of the workbook) has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a.

Sub ScrollBar_CalcPMT()
‘this macro has been assigned to the scroll bars — «Scroll Bar 1» & «Scroll Bar 2» & «Scroll Bar 3» — & will execute when respective scrollbar value changes — refer Image 8a
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its «Scroll Bar 1» in cell C2; Annual Interest (%) in cell B3 & its «Scroll Bar 2» in cell C3; Loan Tenure (Yrs) in cell B4 & its «Scroll Bar 3» in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, shpScrlBar1 As Shape, shpScrlBar2 As Shape, shpScrlBar3 As Shape

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

Set ws = Sheets(«Sheet1»)

ws.Activate

Set shpScrlBar1 = ws.Shapes(«Scroll Bar 1»)

Set shpScrlBar2 = ws.Shapes(«Scroll Bar 2»)

Set shpScrlBar3 = ws.Shapes(«Scroll Bar 3»)

‘set range/cell for ScrollBar

‘cell C2

Set rngScrlBar1 = Range(shpScrlBar1.ControlFormat.linkedCell)

‘cell C3

Set rngScrlBar2 = Range(shpScrlBar2.ControlFormat.linkedCell)

‘cell C4

Set rngScrlBar3 = Range(shpScrlBar3.ControlFormat.linkedCell)

‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:

rngScrlBar1.Offset(0, -1).Value = shpScrlBar1.ControlFormat.Value * 1000

‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:

rngScrlBar2.Offset(0, -1).Value = shpScrlBar2.ControlFormat.Value / 10

‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:

rngScrlBar3.Offset(0, -1).Value = shpScrlBar3.ControlFormat.Value / 2

If Not rngScrlBar1.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Amount!»

Exit Sub

ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Annual Interest Rate!»

Exit Sub

ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Tenure!»

Exit Sub

End If

‘calculate monthly instalment in cell B5:

rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1

End Sub

Example: ActiveX Control ScrollBar(s) & Macro associated with the Change event of the ScrollBar(s):

Add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 8b

Sub ActiveXControl_ScrollBar_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (ScrollBar) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 8b
‘ScrollBar control enables to change (increment or decrement) value in a worksheet range
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($)in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.

Dim ws As Worksheet, rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

‘OLEObject is not used for Form Controls

Dim objScrlBar As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for ScrollBar

Set rngScrlBar1 = Range(«C2»)

Set rngScrlBar2 = Range(«C3»)

Set rngScrlBar3 = Range(«C4»)

With rngScrlBar1.Offset(0, -1).Resize(1, 2)

.Value = ««

.NumberFormat = «$#,##0«

End With

With rngScrlBar2.Offset(0, -1).Resize(2, 2)

.Value = ««

.NumberFormat = «0.0«

End With

With rngScrlBar3.Offset(1, -1)

.Value = «»

.NumberFormat = «$#,##0«

End With

‘delete ActiveX Control ScrollBar objects

For Each objScrlBar In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objScrlBar.Object) = «ScrollBar» Then objScrlBar.Delete

Next objScrlBar

‘delete all (Form Control) Scroll Bars in worksheet

ws.ScrollBars.Delete

rngScrlBar1.ColumnWidth = 15

rngScrlBar1.RowHeight = 15

‘for an already existing ActiveX control ScrollBar, with the name «ScrollBar1»

‘Set objScrlBar = ws.OLEObjects(«ScrollBar1»)

‘set object variable to the newly added ScrollBar ActiveX control — position & size the ScrollBar with the cell assigned to the rngScrlBar1 variable

Set objScrlBar = ws.OLEObjects.Add(ClassType:=»Forms.ScrollBar.1«, DisplayAsIcon:=False, Left:=rngScrlBar1.Left, Top:=rngScrlBar1.Top, Width:=rngScrlBar1.Width, Height:=rngScrlBar1.Height)

With objScrlBar

‘set a String value as object’s name

.Name = «ScrollBar1»

‘set shadow

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘scroll bar will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngScrlBar1.Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘specify the minimum and maximum acceptable values (as integer) of the ScrollBar control (for the Value property setting)

.Min = 0

.Max = 10000

‘Orientation Property determines a vertical ScrollBar or a horizontal ScrollBar. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — ScrollBar dimensions automatically determine whether the ScrollBar is Vertical or Horizontal. Where width is more than height, ScrollBar is Horizontal and where height is more than width, ScrollBar is Vertical; (ii) FmOrientationVertical (Value 0) — vertical ScrollBar; and (iii) FmOrientationHorizontal (Value 1) — horizontal ScrollBar.

.Orientation = fmOrientationHorizontal

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 5

‘LargeChange Property specifies the incremental change, as an integer value, when the user clicks between a scroll arrow and the scroll box. Default value is 1.

.LargeChange = 100
‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 0

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set scroll arrow color to red

.ForeColor = RGB(255, 0, 0)

End With

End With

‘———————-

‘2nd ScrollBar: copy ScrollBar and create new ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar2.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar2.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.OLEObjects(«ScrollBar1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar2.Left

Selection.Top = rngScrlBar2.Top

Selection.Name = «ScrollBar2«

ws.OLEObjects(«ScrollBar2»).linkedCell = rngScrlBar2.Address

With ws.OLEObjects(«ScrollBar2»).Object

.Min = 0

.Max = 500

.SmallChange = 1

.LargeChange = 10

.Value = 0

End With

‘———————-

‘3rd ScrollBar: copy ScrollBar and create new ScrollBar with same properties

‘set range size, for cell below the existing ScrollBar

rngScrlBar3.ColumnWidth = rngScrlBar1.ColumnWidth

rngScrlBar3.RowHeight = rngScrlBar1.Height

‘copy ScrollBar1 to clipboard

ws.OLEObjects(«ScrollBar1»).Copy

‘paste a copy of the ScrollBar in the same sheet

ws.Paste

‘fit new ScrollBar in the cell below the existing ScrollBar

Selection.Left = rngScrlBar3.Left

Selection.Top = rngScrlBar3.Top

Selection.Name = «ScrollBar3«

ws.OLEObjects(«ScrollBar3»).linkedCell = rngScrlBar3.Address

With ws.OLEObjects(«ScrollBar3»).Object

.Min = 0

.Max = 60

.SmallChange = 1

.LargeChange = 4

.Value = 0

End With

End Sub

Macro associated with the Change event of the ScrollBar1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar1)

Private Sub ScrollBar1_Change()
‘Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro associated with the Change event of the ScrollBar2: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar2)

Private Sub ScrollBar2_Change()
‘Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro associated with the Change event of the ScrollBar3: this Event-handler procedure must be located in the code module of the object worksheet containing the control (ScrollBar3)

Private Sub ScrollBar3_Change()
‘Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4

‘calculate monthly instalment:

Call CalcPMT

End Sub

Macro called by the Change events of the 3 ScrollBars: this Event-handler procedure must be located in the code module of the object worksheet containing the controls (ScrollBars) — refer Image 8c.

Sub CalcPMT()
‘Creating a Mortgage Calculator, using ScrollBar controls: Loan Amount ($) in cell B2 & its ScrollBar1 in cell C2; Annual Interest (%) in cell B3 & its ScrollBar2 in cell C3; Loan Tenure (Yrs) in cell B4 & its ScrollBar3 in cell C4; Mthly Instalment ($) in cell B5.

Dim rngScrlBar1 As Range, rngScrlBar2 As Range, rngScrlBar3 As Range

‘set range/cell for ScrollBar

‘cell C2

Set rngScrlBar1 = Range(ScrollBar1.linkedCell)

‘cell C3

Set rngScrlBar2 = Range(ScrollBar2.linkedCell)

‘cell C4

Set rngScrlBar3 = Range(ScrollBar3.linkedCell)

‘in re of Loan Amount, clicking the scroll arrow will increment amount by $5,000 and clicking between a scroll arrow and the scroll box will increment amount by $100,000:

rngScrlBar1.Offset(0, -1).Value = ScrollBar1.Value * 1000

‘in re of Annual Interest Rate, clicking the scroll arrow will increment rate by 0.1% and clicking between a scroll arrow and the scroll box will increment rate by 1%:

rngScrlBar2.Offset(0, -1).Value = ScrollBar2.Value / 10

‘in re of Loan Tenure, clicking the scroll arrow will increment year by 0.5 and clicking between a scroll arrow and the scroll box will increment year by 2:

rngScrlBar3.Offset(0, -1).Value = ScrollBar3.Value / 2

If Not rngScrlBar1.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Amount!»

Exit Sub

ElseIf Not rngScrlBar2.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Annual Interest Rate!»

Exit Sub

ElseIf Not rngScrlBar3.Offset(0, -1).Value > 0 Then

MsgBox «Please Enter Loan Tenure!»

Exit Sub

End If

‘calculate monthly instalment in cell B5:

rngScrlBar3.Offset(1, -1).Value = Pmt((rngScrlBar2.Offset(0, -1).Value / 100) / 12, rngScrlBar3.Offset(0, -1).Value * 12, rngScrlBar1.Offset(0, -1).Value) * -1

End Sub

Example: Form Control SpinButton (Spinner) & Macro to which it is assigned:

Create an Excel Form Control (Spinner) & set Spinner properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control — Refer Image 9a

Sub FormControl_SpinButton_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Spin Button) — this returns a Shape object representing the new control — SpinButton control enables to change (increment or decrement) value in a worksheet range — refer Image 9a.
‘refer Worksheet_Calculate macro — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) so that clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D

Dim ws As Worksheet, rngSpinBtn As Range, shpSpinBtn As Shape, objSpinBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for SpinButton

Set rngSpinBtn = Range(«B2»)

‘delete ActiveX Control SpinButton objects

For Each objSpinBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete

Next objSpinBtn

‘delete Form Control SpinButton objects

For Each shpSpinBtn In ActiveSheet.Shapes

If shpSpinBtn.Type = msoFormControl Then

If shpSpinBtn.FormControlType = xlSpinner Then shpSpinBtn.Delete

End If

Next shpSpinBtn

rngSpinBtn.ColumnWidth = 3

rngSpinBtn.RowHeight = 24

‘for an already existing Form Control shape — SpinButton, with the name «Spinner 1»

‘Set shpSpinBtn = ws.Shapes(«Spinner 1»)

‘set object variable to the newly added SpinButton Form control — position & size the Spin Button with the cell assigned to the rngSpinBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

‘a scroll bar gets oriented (horizontal or vertical) based on its size on the worksheet, whereas an ActiveX SpinButton has an Orientation property which can be set to be Auto, Horizontal, or Vertical

Set shpSpinBtn = ws.Shapes.AddFormControl(xlSpinner, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)

With shpSpinBtn

‘set a String value as object’s name

.Name = «Spinner 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Spin«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘spinner will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property ie. the current value corresponding to the position of the spinner — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

.linkedCell = rngSpinBtn.Address

‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)

.Min = 1

.Max = 100

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 1

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 10

End With

End With

End Sub

Macro associated with the Calculate event of the Spinner: this Event-handler procedure must be located in the code module of the object worksheet containing the control (Spinner 1)

Private Sub Worksheet_Calculate()
‘Worksheet.Change Event is triggered when cells on the worksheet are changed by the user or by an external link — use the Calculate event to trap a sheet recalculation (viz. change in spinner value) — clicking up / down the scroll arrow moves the active cell content one up / one down, in the worksheet column D

Application.EnableEvents = False

On Error GoTo ErrorHandler

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then GoTo ErrorHandler

Static PrevValue As Variant

Dim rng As Range

Dim strSpinDir As String

Dim str1 As String, str2 As String

Set rng = ActiveCell

If Shapes(«Spinner 1»).ControlFormat.Value < PrevValue Then

MsgBox «SpinDown»

str1 = rng.Value

str2 = rng.Offset(1, 0)

rng.Value = str2

rng.Offset(1, 0) = str1

rng.Offset(1, 0).Select

ElseIf Shapes(«Spinner 1»).ControlFormat.Value > PrevValue Then

‘if active cell is D1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then

Shapes(«Spinner 1»).ControlFormat.Value = 10

PrevValue = Shapes(«Spinner 1»).ControlFormat.Value

GoTo ErrorHandler

End If

MsgBox «SpinUp»

str1 = rng.Value

str2 = rng.Offset(-1, 0)

rng.Value = str2

rng.Offset(-1, 0) = str1

rng.Offset(-1, 0).Select

End If

‘set spin button value, in variance from its Min or Max

Shapes(«Spinner 1»).ControlFormat.Value = 10

PrevValue = Shapes(«Spinner 1»).ControlFormat.Value

Application.EnableEvents = True

ErrorHandler:

Application.EnableEvents = True

End Sub

Example: ActiveX Control SpinButton & Macros associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow: 

Add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 9b

Sub ActiveXControl_SpinButton_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (SpinButton) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 9b
‘refer event handler procedures of SpinButton1_SpinDown & SpinButton1_SpinUp, associated with the events of the SpinDown & SpinUp ie. clicking down / up the scroll arrow.

Dim ws As Worksheet, rngSpinBtn As Range

‘OLEObject is not used for Form Controls

Dim objSpinBtn As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for SpinButton

Set rngSpinBtn = Range(«B2»)

‘delete ActiveX Control SpinButton objects

For Each objSpinBtn In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objSpinBtn.Object) = «SpinButton» Then objSpinBtn.Delete

Next objSpinBtn

rngSpinBtn.ColumnWidth = 3

rngSpinBtn.RowHeight = 24

‘for an already existing ActiveX control SpinButton, with the name «SpinButton1»

‘Set objSpinBtn = ws.OLEObjects(«SpinButton1»)

‘set object variable to the newly added SpinButton ActiveX control — position & size the SpinButton with the cell assigned to the rngSpinBtn variable

Set objSpinBtn = ws.OLEObjects.Add(ClassType:=»Forms.SpinButton.1«, DisplayAsIcon:=False, Left:=rngSpinBtn.Left, Top:=rngSpinBtn.Top, Width:=rngSpinBtn.Width, Height:=rngSpinBtn.Height)

With objSpinBtn

‘set a String value as object’s name

.Name = «SpinButton1«

‘no shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘SpinButton will be printed when the document is printed

.PrintObject = True

‘LinkedCell Property specifies a cell to set or store the Value property — changing the value of the control will automatically update the linked cell & a change in the linked cell will update the value of the control.

‘set no linked cell

.linkedCell = ««

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘specify the minimum and maximum acceptable values (as integer) of the SpinButton control (for the Value property setting)

.Min = 1

.Max = 100

‘Orientation Property determines a vertical SpinButton or a horizontal SpinButton. It has 3 settings: (i) fmOrientationAuto (Value -1, default) — SpinButton dimensions automatically determine whether the SpinButton is Vertical or Horizontal. Where width is more than height, SpinButton is Horizontal and where height is more than width, SpinButton is Vertical; (ii) FmOrientationVertical (Value 0) — vertical SpinButton; and (iii) FmOrientationHorizontal (Value 1) — horizontal SpinButton.

.Orientation = fmOrientationVertical

‘SmallChange Property specifies the incremental change, as an integer value, that occurs when a user clicks the scroll arrow. Default value is 1.

.SmallChange = 1

‘Value property sets the control’s current value, which is an integer between maximum & minimum values specified in the Max and Min properties

.Value = 1

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set background color to yellow

.BackColor = RGB(255, 255, 0)

‘set scroll arrow color to red

.ForeColor = RGB(255, 0, 0)

End With

End With

End Sub

Macro associated with the event of SpinDown ie. clicking down the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)

Private Sub SpinButton1_SpinDown()
‘clicking down the scroll arrow moves the active cell content one down in the worksheet column D

On Error Resume Next

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub

‘spin button value remains constant

SpinButton1.Value = 1

Dim rng As Range, str1 As String, str2 As String

Set rng = ActiveCell

str1 = rng.Value

str2 = rng.Offset(1, 0)

rng.Value = str2

rng.Offset(1, 0) = str1

rng.Offset(1, 0).Select

End Sub

Macro associated with the event of SpinUp ie. clicking up the scroll arrow of SpinButton1: this Event-handler procedure must be located in the code module of the object worksheet containing the control (SpinButton1)

Private Sub SpinButton1_SpinUp()
‘clicking up the scroll arrow moves the active cell content one up in the worksheet column D

On Error Resume Next

‘if active cell is not in column D, then exit procedure

If Application.Intersect(ActiveCell, Range(«D:D»)) Is Nothing Then Exit Sub

‘if active cell is D1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«D1»)) Is Nothing Then Exit Sub

‘spin button value remains constant

SpinButton1.Value = 1

Dim rng As Range, str1 As String, str2 As String

Set rng = ActiveCell

str1 = rng.Value

str2 = rng.Offset(-1, 0)

rng.Value = str2

rng.Offset(-1, 0) = str1

rng.Offset(-1, 0).Select

End Sub

TextBox — ActiveX Control

A TextBox is a rectangular box, wherein you may type, edit or view text or data, or it may also be a static text field displaying read-only information. Below we illustrate an ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox.

Example: ActiveX Control TextBox & Macro associated with the GotFocus event of the TextBox:

Add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 10a

Sub ActiveXControl_TextBox_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (TextBox) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — refer Image 10a

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objTB As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

Set rng = ws.Range(«A11»)

‘delete ActiveX Control ScrollBar objects

For Each objTB In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objTB.Object) = «TextBox» Then objTB.Delete

Next objTB

‘for an already existing ActiveX control checkbox, with the name «TextBox1»

‘Set objTB = ws.OLEObjects(«TextBox1»)

‘set object variable to the newly added check box ActiveX control — position the check box with the cell assigned to the rng variable

Set objTB = ws.OLEObjects.Add(ClassType:=»Forms.TextBox.1«, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=150, Height:=40)

With objTB

‘set a String value as object’s name

.Name = «TextBox1«

‘set shadow

.Shadow = False

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘Enabled Property of a TextBox should be set to False if you do not want to allow the user to type directly into the TextBox which should be filled only per the user-selected option, say from a ListBox

.Enabled = True

‘TextBox will be printed when the document is printed

.PrintObject = True

‘the text or value in the TextBox will get stored in this worksheet cell

.linkedCell = rng.Offset(-2, 0).Address

‘wrt to the cell which is under the upper-left corner of the textbox

MsgBox .TopLeftCell.Address

‘wrt to the cell which is under the lower-right corner of the textbox

MsgBox .BottomRightCell.Address

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘enabling the DragBehavior property enables the drag-and-drop feature for TextBox — dragging in text box starts a drag-and-drop operation on the selected text

.DragBehavior = fmDragBehaviorEnabled

‘EnterKeyBehavior Property: A Boolean value (True/False) which determines the effect when a user presses the ENTER key in a TextBox. If MultiLine property is set to True, then the True value indicates creating a new line on pressing ENTER while the False value (Default) moves focus to the next control in the tab order. If MultiLine property is set to False, then focus is always moved to the next control in the tab order ignoring the EnterKeyBehavior Property.

.EnterKeyBehavior = True

‘if MultiLine is True, set TabKeyBehavior property to True whereby pressing ENTER inserts a Tab and set to False (default) whereby pressing ENTER moves the focus to the next object in the tab order; If MultiLine is False, pressing ENTER will always move the focus to the next control in the tab order.

.TabKeyBehavior = True

‘set SelectionMargin property to True: selection margin occupies a thin strip along the left edge of the control’s edit region, & set to False for the entire edit region to store text.

.SelectionMargin = False

.MultiLine = True

‘caption text will wrap to the next line

.WordWrap = True

‘AutoSize setting for TextBox: (i) if the TextBox is single-line, AutoSize resizes width of TextBox to the length of the text; (ii) if the TextBox is MultiLine with no text, AutoSize resizes width to display single letter (of widest width of that font size) and resizes height to display the entire text; and (iii) if the TextBox is MultiLine with text present, AutoSize does not change the width of the TextBox and resizes height to display the entire text.

.AutoSize = False

‘ScrollBars Property: Specifies whether a TextBox has vertical and/or horizontal scroll bars, or none. There are 4 self-explanatory settings: (i) fmScrollBarsNone (value 0) — default; (ii) fmScrollBarsHorizontal (value 1); (iii) fmScrollBarsVertical (value 2); and (iv) fmScrollBarsBoth (value 3). The scroll bar setting fmScrollBarsNone displays no scroll bar. If AutoSize is set to True, no scroll bar is diplayed because the TextBox enlarges itself to accommodate the additional text or data. If WordWrap is set to True, a multiline TexBox displays no horizontal scroll bar. The scroll bar settings fmScrollBarsHorizontal or fmScrollBarsBoth, display a horizontal scroll bar in a singleline TextBox if the text is longer than the edit region. The scroll bar settings fmScrollBarsVertical or fmScrollBarsBoth, display a vertical scroll bar in a multiline TextBox if the text is longer than the edit region and WordWrap is set to True. To display a horizontal scroll bar in a multiline TexBox, the scroll bar setting should be fmScrollBarsHorizontal, WordWrap should be set to False and the text should be longer than the edit region. Note 1: A horizontal (or vertical) scroll bar is visible only if the control has enough room to include the scroll bar under (or at the right edge of) its edit region.

.ScrollBars = 2

‘text alignment set to center

.TextAlign = fmTextAlignCenter

‘specify characters displayed in TextBox instead of the characters actually entered

‘.PasswordChar = «*«

‘MaxLength property specifies the maximum number of characters which can be entered by the user in a TextBox — set maximum length for password field

‘.MaxLength = 5

‘use the Text property to set text in a TextBox — a value assigned to the Text property gets automatically assigned to the Value property, and vice-versa.

.Text = «Hello»

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘set the background color for control to yellow

.BackColor = RGB(255, 255, 0)

‘set font color to red

.ForeColor = RGB(255, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

‘set border

.BorderStyle = fmBorderStyleSingle

.BorderColor = vbBlue

With .Font

.Name = «Arial«

.Bold = True

.Size = 10

.Italic = False

.Underline = False

End With

End With

End With

End Sub

Macro associated with the GotFocus event of the TextBox: this Event-handler procedure must be located in the code module of the object worksheet containing the control (TextBox1) — refer Image 10b.

Private Sub TextBox1_GotFocus()
‘if the active cell is in the worksheet column A (except cell A1), then focus on the TextBox (ex. selecting the TextBox) will set text in the TextBox — refer Image 10b (selecting Jack in column A & then selecting TextBox)

On Error Resume Next

‘if active cell is not in column A, then exit procedure

If Application.Intersect(ActiveCell, Range(«A:A»)) Is Nothing Then Exit Sub

‘if active cell is A1, then exit procedure

If Not Application.Intersect(ActiveCell, Range(«A1»)) Is Nothing Then Exit Sub

If ActiveCell.Value <> «» Then

TextBox1.Text = ActiveCell.Value & «‘s height is » & ActiveCell.Offset(0, 1).Value & » cms & weight is » & ActiveCell.Offset(0, 2).Value & » kg»

End If

End Sub

Label — Form Control or ActiveX Control

Label stores text which is not editable by user, and is used to describe other controls (often a TextBox) or purpose of a worksheet cell or to provide instructions — you may display any descriptive text like caption, title or pictures in a Label.

Below we illustrate: (i) a Form Control Label; and (ii) an ActiveX Control Label.

Example: Form Control Label:

Create an Excel Form Control (Label) & set its properties — use Shapes.AddFormControl Method to create an Excel Form Control which returns a Shape object representing the new control

Sub FormControl_Label_Shape_Properties()
‘use Shapes.AddFormControl Method to create an Excel Form Control (Label) — this returns a Shape object representing the new control

Dim ws As Worksheet, rngLbl As Range, shpLbl As Shape, objLbl As OLEObject

Set ws = Sheets(«Sheet1»)

ws.Activate

‘set range/cell for Label

Set rngLbl = Range(«E15»)

‘delete ActiveX Control Label objects

For Each objLbl In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLbl.Object) = «Label» Then objLbl.Delete

Next objLbl

‘delete Form Control Label objects

For Each shpLbl In ActiveSheet.Shapes

If shpLbl.Type = msoFormControl Then

If shpLbl.FormControlType = xlLabel Then shpLbl.Delete

End If

Next shpLbl

rngLbl.ColumnWidth = 10

rngLbl.RowHeight = 18

‘for an already existing Form Control Label, with the name «Label 1»

‘Set shpLbl = ws.Shapes(«Label 1»)

‘set object variable to the newly added Label Form control — position & size the Label with the cell assigned to the rngSpinBtn variable

‘use Shapes.AddFormControl Method to create an Excel Form Control — this returns a Shape object representing the new control — Syntax: Shapes.AddFormControl(Type, Left, Top, Width, Height):

Set shpLbl = ws.Shapes.AddFormControl(xlLabel, Left:=rngLbl.Left, Top:=rngLbl.Top, Width:=rngLbl.Width, Height:=rngLbl.Height)

With shpLbl

‘set a String value as object’s name

.Name = «Label 1«

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

‘shape will retain its original proportions when it is resized

.LockAspectRatio = msoTrue

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = «Label1«

‘use the Caption property to display text

.OLEFormat.Object.Caption = «Country«

‘alternatively:

‘TextFrame Property returns a TextFrame object which contains the alignment & anchoring properties for a shape — valid for only a shape having a text frame

.TextFrame.Characters.Text = «USA«

‘ControlFormat property of the Shape object returns a ControlFormat object that contains Microsoft Excel control properties — the ControlFormat property will fail if the shape is not a control.

With .ControlFormat

.Enabled = True

‘label will be printed when the document is printed

.PrintObject = True

End With

End With

End Sub

Example: ActiveX Control Label:

Add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11.

Sub ActiveXControl_Label_OLEobject_Properties()
‘add a new OLEObject to a sheet — ActiveX control (Label) — set its properties by using the properties of an OLEObject object, & by using the Object property of the OLEObject object — Refer Image 11
‘Label stores text which is not editable by user, and is used to describe other controls — in the Image, Labels are in Green color & describe OptionButtons to their right.

Dim ws As Worksheet, rng As Range

‘OLEObject is not used for Form Controls

Dim objLbl As OLEObject

Set ws = Sheets(«Sheet11»)

ws.Activate

Set rng = Union(Range(«A5»), Range(«A6»))

‘delete ActiveX Control Label objects

For Each objLbl In ActiveSheet.OLEObjects

‘TypeName Function returns the data-type about a variable — TypeName(varname)

If TypeName(objLbl.Object) = «Label» Then objLbl.Delete

Next objLbl

‘for an already existing ActiveX control Label, with the name «Label1»

‘Set objLbl = ws.OLEObjects(«Label1»)

‘set object variable to the newly added Label ActiveX control — position the Label with the cell assigned to the rng variable

Set objLbl = ws.OLEObjects.Add(ClassType:=»Forms.Label.1″, DisplayAsIcon:=False, Left:=rng.Left, Top:=rng.Top, Width:=rng.Width, Height:=rng.Height)

With objLbl

‘set a String value as object’s name

.Name = «Label1«

.Shadow = True

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

.Locked = True

.Enabled = True

‘label will be printed when the document is printed

.PrintObject = True

‘if the property is not listed under the OLEObject class in the Object Browser, then you must return the actual control object by using the Object property of the OLEObject object

‘Object Property of the OLEObject returns a OLE Automation object associated with this OLE object

With .Object

‘text alignment (horizontal) set to center — note there is no specific property to vertically align text within a label

.TextAlign = fmTextAlignCenter

‘use the Caption property to display text

.Caption = «Europe«

‘determines how the control visually appears

.SpecialEffect = fmButtonEffectFlat

‘specify type of mouse pointer

.MousePointer = fmMousePointerArrow

‘caption text will wrap to the next line

.WordWrap = True

‘setting AutoSize to True automatically resizes the Caption while False (Default option) keeps the caption size constant wherein content exceeding the control area gets cut.

.AutoSize = False

‘set the background color for control to green

.BackColor = RGB(0, 255, 0)

‘set font color to black

.ForeColor = RGB(0, 0, 0)

‘set background to be Opaque or Transparent — BackStyle property should be set to fmBackStyleOpaque for the BackColor to have any effect

.BackStyle = fmBackStyleOpaque

‘set border

.BorderStyle = fmBorderStyleSingle

‘set border color

.BorderColor = vbBlue

With .Font

.Name = «Arial«

.Bold = True

.Size = 8

.Italic = False

.Underline = False

End With

End With

End With

‘copy Label1 to clipboard

ws.OLEObjects(«Label1»).Copy

‘paste a copy of the Label in the same sheet

ws.Paste

‘position new Label

Selection.Left = Range(«A2»).Left

Selection.Top = Range(«A2»).Top

Selection.Name = «Label2»

ws.OLEObjects(«Label2»).Object.Caption = «America«

End Sub

Illustrating Auto Shapes, Add a connector

Example: Illustrating Auto Shapes, add a connector — refer Image 12  — use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape

Sub AutoShapes_Shape_Properties()
‘illustrating Auto Shapes, add a connector — refer Image 12
‘Use the Shapes.AddShape Method to Add  a new AutoShape — this returns a Shape object that representing the new AutoShape — Syntax: Shapes.AddShape(Type, Left, Top, Width, Height). The Type argument specifies the shape type per the MsoAutoShapeType Enumeration

Dim ws As Worksheet

Dim shp As Shape, shpRectangle As Shape, shpTriangle As Shape, shpOval As Shape, shpRightArrow As Shape, shpConn As Shape

Dim rngRectangle As Range, rngTriangle As Range, rngOval As Range, rngRightArrow As Range

Set ws = Sheets(«Sheet1»)

‘———————————

‘delete all auto shapes

For Each shp In ws.Shapes

If shp.Type = msoAutoShape Then

‘MsgBox shp.Name & «, » & shp.AutoShapeType

shp.Delete

End If

Next

‘———————————

‘add 4 shapes in worksheet — Rectangle, Triangle, Oval & Right Arrow:

‘set range/cell for ToggleButton

Set rngRectangle = Range(«B3»)

Set rngTriangle = rngRectangle.Offset(2, 0)

Set rngOval = rngRectangle.Offset(4, 0)

Set rngRightArrow = rngRectangle.Offset(6, 0)

‘Range.ColumnWidth Property returns or sets the width of all columns in the specified range, where one unit of column width is equal to the width of one character in the Normal style (width of the character zero is used for proportional fonts) — to return (does not set) the width of the range in points, use the Range.Width property

rngRectangle.ColumnWidth = 18

‘Range.RowHeight Property returns or sets the height of the first row in the range, in points — to set or return the total height of a range of cells in points, use the Height property.

rngRectangle.RowHeight = 24

rngTriangle.RowHeight = 36

rngOval.RowHeight = 55

rngRightArrow.RowHeight = 18

‘for an already existing ActiveX control ToggleButton, with the name «ToggleButton1»

‘Set shpRectangle = ws.shapes(«Rectangle 1»)

‘set object variable to the newly added ToggleButton ActiveX control — position & size the Rectangle with the cell assigned to the rngRectangle variable

Set shpRectangle = ws.Shapes.AddShape(Type:=msoShapeRectangle, Left:=rngRectangle.Left, Top:=rngRectangle.Top, Width:=rngRectangle.Width, Height:=rngRectangle.Height)

shpRectangle.Name = «Rectangle 1«

Set shpTriangle = ws.Shapes.AddShape(Type:=msoShapeIsoscelesTriangle, Left:=rngTriangle.Left, Top:=rngTriangle.Top, Width:=rngTriangle.Width, Height:=rngTriangle.Height)

shpTriangle.Name = «Triangle 1«

Set shpOval = ws.Shapes.AddShape(Type:=msoShapeOval, Left:=rngOval.Left, Top:=rngOval.Top, Width:=rngOval.Width, Height:=rngOval.Height)

shpOval.Name = «Oval 1«

Set shpRightArrow = ws.Shapes.AddShape(Type:=msoShapeRightArrow, Left:=rngRightArrow.Left, Top:=rngRightArrow.Top, Width:=30, Height:=rngRightArrow.Height)

shpRightArrow.Name = «Right Arrow 1«

‘refer Shapes collection ie. Shapes object

‘returns 4 (there are four shapes in the collection)

MsgBox ws.Shapes.Count

‘———————————

‘set some common properties for all shapes

‘refer each Shape object

For Each shp In ws.Shapes

‘shape will retain its original proportions when it is resized

shp.LockAspectRatio = msoTrue

‘Placement property determines how the object is attached to its underlying cells viz. xlFreeFloating (Object is free floating — does not move or size with cells), xlMove (Object is moved with the cells), xlMoveAndSize (Object is moved and sized with the cells)

shp.Placement = xlFreeFloating

‘use the Locked Property of the Shapes object to lock it — if not Locked (False), the object can be modified when the sheet is protected

shp.Locked = True

‘MsgBox shp.Name

‘shape will be printed when the document is printed

shp.OLEFormat.Object.PrintObject = True

Next shp

‘———————————

‘set properties for Rectangle shape

With shpRectangle

‘indicates the ThreeDFormat object is visible

.ThreeD.Visible = msoTrue

‘use the BevelTopType Property of the ThreeDFormat object to set the type of top bevel, as per the constants defined in MsoBevelType Enumeration: msoBevelCircle, msoBevelSlope, msoBevelSoftRound, msoBevelConvex, …

.ThreeD.BevelTopType = msoBevelCircle

‘set the width & height of the bevel using the BevelTopInset & BevelTopWidth values respectively — this means setting the width & height of the raised edge at the top of a shape

‘set width to 10 points

.ThreeD.BevelTopInset = 10

‘set height to 5 points

.ThreeD.BevelTopDepth = 5

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

.AlternativeText = .Name

‘set fill / interior

With .Fill

.Visible = msoTrue

.Solid

‘.ForeColor.SchemeColor = 13

.ForeColor.RGB = RGB(255, 255, 0)

.Transparency = 0

End With

‘set border

With .Line

‘.Weight = 1

.DashStyle = msoLineSolid

.Style = msoLineSingle

.Transparency = 0

‘.ForeColor.SchemeColor = 10

.ForeColor.RGB = RGB(0, 255, 0)

End With

‘set text

With .TextFrame

‘.HorizontalAlignment = xlHAlignCenter

.HorizontalAlignment = xlHAlignLeft

‘.VerticalAlignment = xlVAlignDistributed

.VerticalAlignment = xlVAlignCenter

.Characters.Text = «Rectangle«

With .Characters.Font

.Name = «Arial«

.ColorIndex = 5

.Size = 11

.Bold = True

.Italic = False

End With

.Characters(Start:=1, Length:=1).Font.ColorIndex = 3

End With

End With

‘———————————
‘set properties for Triangle shape

With shpTriangle

‘set the alternative text to a shape description when Shape object is saved to a Web page — alternative text may be displayed in the web browser in lieu of the shape’s image, or over the shape’s image when the mouse pointer hovers over the image (if browser supported).

‘shpTriangle.Name is «Triangle 1»

.AlternativeText = .Name

‘set fill / interior

With .Fill

.Visible = msoTrue

‘yellow

.ForeColor.SchemeColor = 13

.Transparency = 0.2

End With

‘set border

With .Line

‘to not display border, use msoFalse

.Visible = msoTrue

.Weight = 1

.DashStyle = msoLineDash

.Transparency = 0

.ForeColor.SchemeColor = 10

End With

‘set text to display caption — first 8 letters of shpTriangle.Name

.OLEFormat.Object.Caption = Left(shpTriangle.Name, 8)

With .OLEFormat.Object.Font

.Name = «Arial«

.Bold = True

.Size = 8

.Italic = False

.ColorIndex = 5

End With

.OLEFormat.Object.Shadow = True

With .Shadow

‘use the Style Property of the ShadowFormat object to set the type of shadowing effect, as per the style constants defined in the MsoShadowStyle Enumeration

.Style = msoShadowStyleOuterShadow

‘use the ForeColor Property of the ShadowFormat object to set the fill color for the shadow

.ForeColor.RGB = RGB(255, 0, 0)

.Blur = 2

‘use the Size Property of the ShadowFormat object to set a value representing the percentage size for the shadow

.Size = 90

‘the OffsetX Property of the ShadowFormat object sets a value, in points, indicating the horizontal offset of the shadow to the chart area, with a negative value offsetting the shadow to the left

.OffsetX = 6

‘the OffsetY Property of the ShadowFormat object sets a value, in points, indicating the vertical offset of the shadow to the chart area, with a negative value offsetting the shadow to the above

.OffsetY = -5

‘the Transparency Property of the ShadowFormat object sets the degree of the transparency in a fill, as a value from 0.0 (opaque) to 1.0 (clear), for solid color fills

.Transparency = 0.2

End With

End With

‘———————————

‘Oval shape: set an image to the specified fill

With shpOval.Fill

‘using the ChartFillFormat.UserPicture Method to fill the shape with an image — specify filename & path of image file

.UserPicture «C:UsersamitDocumentsPhotosDollar.jpg»

End With

‘———————————

‘Right Arrow shape:

With shpRightArrow

.Fill.ForeColor.RGB = RGB(0, 0, 255)

.ThreeD.BevelTopType = msoBevelConvex

‘to not display border, use msoFalse

.Line.Visible = msoFalse

‘use the Shape.OnAction Property to assign a macro (ie. sets the macro name) to the shape — clicking on shpRightArrow will execute the NextStep macro

.OnAction = «NextStep«

End With

‘———————————

‘add the connector in 5 steps:

‘To add a connector: 1) Add a connector shape; 2) specify the shape it begins at; 3) specify the shape it ends at; 4) reroute the connector given the position of the 2 shapes which it links; 5) format the connector;

‘use the Shapes.AddConnector Method to create a connector — this method returns a Shape object representing the new connector. Syntax: Shapes.AddConnector(Type, BeginX, BeginY, EndX, EndY) — use the Type argument to specify the connectr type (msoConnectorCurve, msoConnectorElbow, msoConnectorStraight). The BeginX & EndX arguments specify the horizontal position (in points) of the start & end points relative to the upper-left corner of the document & the BeginY & EndY arguments specify the vertical position (in points) of the start & end points relative to the upper-left corner of the document. All arguments are necessary to specify.

‘The new connector added does not connect anything — you will need to use the BeginConnect & EndConnect methods to specify shapes where the connector begins & ends at.

‘add the connector (curved connector) without regard to its position or size as it will be redrawn later.

Set shpConn = ws.Shapes.AddConnector(msoConnectorCurve, 1, 1, 1, 1)

Dim iLastSite As Integer

iLastSite = shpOval.ConnectionSiteCount

With shpConn

‘use the ConnectorFormat.BeginConnect Method to attach the beginning of the connector to a shape — Syntax: ConnectorFormat.BeginConnect(ConnectedShape, ConnectionSite) — the ConnectedShape argument specifies the shape to which the beginning of the connector is attached to. The ConnectionSite argument specifies the number (Integer) of the connection site on the shape between 1 and the number of connection sites on a shape (which can be returned by using the Shape.ConnectionSiteCount Property).

‘attach the beginning of the connector to connection site 2 on the shpTriangle & the attach the connector end to the last connection site of the shpOval

.ConnectorFormat.BeginConnect shpTriangle, 2

‘use the ConnectorFormat.EndConnect Method to attach the end of the connector to a shape

.ConnectorFormat.EndConnect shpOval, iLastSite

‘use the ShapeRange.RerouteConnections Method to reroute the connector so as to take the shortest possible path between the shapes it connects, and for this the ends of a connector may be reattached to different connecting sites on the connected shapes.

‘.RerouteConnections

‘format the connector — set color to red & thickness to 2 pts

.Line.ForeColor.RGB = RGB(255, 0, 0)

.Line.Weight = 2

End With

End Sub

Using ActiveX Controls on Sheets

This topic covers specific information about using ActiveX controls on worksheets and chart sheets. For general information on adding and working with controls, see Using ActiveX Controls on a Document
and Creating a Custom Dialog box.

Keep the following points in mind when you are working with controls on sheets.

  • In addition to the standard properties available for ActiveX controls, the following properties can be used with ActiveX controls in Microsoft Excel: BottomRightCell, LinkedCell, ListFillRange, Placement, PrintObject, TopLeftCell, and ZOrder.

    These properties can be set and returned using the ActiveX control name. The following example scrolls the workbook window so CommandButton1 is in the upper-left corner.

    Set t = Sheet1.CommandButton1.TopLeftCell
    With ActiveWindow
        .ScrollRow = t.Row
        .ScrollColumn = t.Column
    End With
    				
  • Some Microsoft Excel Visual Basic methods and properties are disabled when an ActiveX control is activated. For example, the Sort method cannot be used when a control is active, so the following code fails in a button click event procedure (because the control is still active after the user clicks it).
    Private Sub CommandButton1.Click
        Range("a1:a10").Sort Key1:=Range("a1")
    End Sub
    				

You can work around this problem by activating some other element on the sheet before you use the property or method that failed. For example, the following code sorts the range:

Private Sub CommandButton1.Click
    Range("a1").Activate
    Range("a1:a10").Sort Key1:=Range("a1")
    CommandButton1.Activate
End Sub
		
  • Controls on a Microsoft Excel workbook embedded in a document in another application will not work if the user double clicks the workbook to edit it. The controls will work if the user right clicks the workbook and selects the Open command from the shortcut menu.
  • When a Microsoft Excel workbook is saved using the Microsoft Excel 5.0/95 Workbook file format, ActiveX control information is lost.
  • The Me keyword in an event procedure for an ActiveX control on a sheet refers to the sheet, not to the control.

Adding Controls with Visual Basic

In Microsoft Excel, ActiveX controls are represented by OLEObject objects in the OLEObjects collection (all OLEObject objects are also in the Shapes collection). To programmatically add an ActiveX control to a sheet, use the Add method of the OLEObjects collection. The following example adds a command button to worksheet one.

Worksheets(1).OLEObjects.Add "Forms.CommandButton.1", _
    Left:=10, Top:=10, Height:=20, Width:=100
		

Using Control Properties with Visual Basic

Most often, your Visual Basic code will refer to ActiveX controls by name. The following example changes the caption on the control named «CommandButton1.»

Sheet1.CommandButton1.Caption = "Run"
		

Note that when you use a control name outside the class module for the sheet containing the control, you must qualify the control name with the sheet name.

To change the control name you use in Visual Basic code, select the control and set the (Name) property in the Properties window.

Because ActiveX controls are also represented by OLEObject objects in the OLEObjects collection, you can set control properties using the objects in the collection. The following example sets the left position of the control named «CommandButton1.»

Worksheets(1).OLEObjects("CommandButton1").Left = 10
		

Control properties that are not shown as properties of the OLEObject object can be set by returning the actual control object using the Object property. The following example sets the caption for CommandButton1.

Worksheets(1).OLEObjects("CommandButton1"). _
    Object.Caption = "run me"
		

Because all OLE objects are also members of the Shapes collection, you can use the collection to set properties for several controls. The following example aligns the left edge of all controls on worksheet one.

For Each s In Worksheets(1).Shapes
    If s.Type = msoOLEControlObject Then s.Left = 10
Next
		

Using Control Names with the Shapes and OLEObjects Collections

An ActiveX control on a sheet has two names: the name of the shape that contains the control, which you can see in the Name box when you view the sheet, and the code name for the control, which you can see in the cell to the right of (Name) in the Properties window. When you first add a control to a sheet, the shape name and code name match. However, if you change either the shape name or code name, the other isn’t automatically changed to match.

You use the code name of a control in the names of its event procedures. However, when you return a control from the Shapes or OLEObjects collection for a sheet, you must use the shape name, not the code name, to refer to the control by name. For example, assume that you add a check box to a sheet and that both the default shape name and the default code name are CheckBox1. If you then change the control code name by typing chkFinished next to (Name) in the Properties window, you must use chkFinished in event procedures names, but you still have to use CheckBox1 to return the control from the Shapes or OLEObject collection, as shown in the following example.

Private Sub chkFinished_Click()
    ActiveSheet.OLEObjects("CheckBox1").Object.Value = 1
End Sub
		

When we are automating an excel sheet with VBA at that time when the user has a requirement for a more flexible design then it’s better to use ActiveX Controller. In Excel user has to add the ActiveX Controller manually and ActiveX Controls are used as objects in codes. There are the following types of ActiveX Controls that are important:

  • Text Box
  • List Box
  • Combo Box
  • Check Box

How to Create ActiveX Control in Excel VBA?

To do some changes in the excel sheet using ActiveX control we need to use the Command-click button for that we have to follow further steps

Step 1: Select the developer tab and click Insert drop-down list from the control box.

Clicking-control-box

Step 2: Choose the command button from ActiveX Controls Box.

Clicking-command-button

Step 3: Draw the command button in the excel sheet.

Drawing-command-button

Step 4: Right-click on the command button and select view code to write the VBA code.

Selecting-view-code

Step 5: When the user will click on Command Button they should get their respective values in the cell. So for that, we have to write codes in VBA.

Writing-code-in-vba

In the VBA code, we can write codes in different ways to get the action done by VBA on clicking the command button which we have discussed in the following 

Text Box

It is a type of ActiveX Controls which is used to fill the empty field with text which is useful for us to get the details of the input from the user such as name, year, department, date of birth, etc by the text of the box

Step 1: Select the Text Box from the ActiveX Controls box.

Selecting-text-box

Step 2: Draw the Text Box in the excel sheet and then right-click on the box to select view code.

Selecting-view-code

Step 3: Write a code in VBA to create a Text Box with a name so that it can be used to access the inputs given by a user.

Writing-code-in-vba

List Box

It helps us to fill a box with a list of values so that we can users can select any value from it for that we have to follow further steps.

Step 1: Select the List Box from the ActiveX Controls box.

selecting-list-box

Step 2: Draw the List Box in the excel sheet and then right-click on the box to select view code.

Selecting-view-code

Step 3: Write a code in VBA to add items to the list box.

Writing-code-in-vba

Combo Box

It is used to make a drop-down list where the user can select an item from the drop-down list for that we have to follow further steps.

Step 1: Select the Combo Box from the ActiveX Controls box.

selecting-combo-box

Step 2: Draw the Combo Box in the excel sheet and then right-click on the box to select the view code.

Selecting-view-code

Step 3: Write a code in VBA to add items to the combo box.

Writing-code-in-vba

Check Box

It is used to create a check box where a list of values is stored which gets visible upon selecting the check box for that we have to follow further steps.

Step 1: Select the Check Box from the ActiveX Controls box.

selecting-check-box

Step 2: Draw the Check Box in the excel sheet and then right-click on the box to select view code.

Selecting-view-code

Step 3: Write a code to display the value when a check box is marked.

Writing-code-in-vba

Понравилась статья? Поделить с друзьями:
  • Activex component can create object excel 429
  • Activeworkbook saveas vba excel
  • Activewindow zoom excel vba
  • Activesheet vba excel это
  • Activesheet usedrange vba excel