Получите сведения о работе с элементами ActiveX в файлах, изменении их параметров, а также о включении и отключении их с помощью панели сообщений и центра управления безопасностью. Кроме того, вы можете получить дополнительные сведения об элементах ActiveX и о том, как они позволяют улучшить файлы.
ИТ-специалисты могут найти дополнительные сведения о планировании элементов ActiveX в статье TechNet Планирование параметров безопасности для элементов управления ActiveX в приложениях Office 2010.
В этой статье
-
Включение элементов ActiveX при появлении панели сообщений
-
Включение элементов ActiveX на один раз при появлении предупреждения системы безопасности
-
Изменение параметров элементов ActiveX в Word, Access, Excel, PowerPoint, Publisher и Visio
-
Описание параметров элементов ActiveX
-
Что представляет собой элемент ActiveX, и какие риски с ним связаны
-
Риск и возможные последствия
Включение элементов ActiveX при появлении панели сообщений
При открытии файла с элементами ActiveX появляется желтая панель сообщений со значком щита и кнопкой Включить содержимое. Если известно, что источник элементов является надежным, воспользуйтесь описанными ниже инструкциями.
-
В области Панель сообщений нажмите кнопку Включить содержимое.
Файл откроется в качестве надежного документа.
На приведенном ниже рисунке показан пример панели сообщений, если в файле есть элементы ActiveX.
К началу страницы
Включение элементов ActiveX в представлении Backstage
Другой способ включения элементов ActiveX в файле — с помощью представления Microsoft Office Backstage, которое появляется после открытия вкладки Файл при отображении желтой панели сообщений.
-
Откройте вкладку Файл.
-
В области Предупреждение системы безопасности нажмите кнопку Включить содержимое.
-
В разделе Включить все содержимое выберите команду Всегда включать активное содержимое данного документа.
Файл станет надежным документом.
На приведенном ниже рисунке показаны команды Всегда включать активное содержимое этого документа и Дополнительные параметры.
На приведенном ниже рисунке показаны команды группы Включить содержимое.
Примечание: Исключение составляют элементы ActiveX с флагом блокировки. Такие элементы ActiveX не запускаются. Флаг блокировки — это функция безопасности, которая запрещает элементу ActiveX использовать код ActiveX, например устраняя уязвимость в системе безопасности или предотвращая запуск кода.
К началу страницы
Включение элементов ActiveX на один раз при появлении предупреждения системы безопасности
Выполнив приведенные ниже инструкции, можно включить элементы управления на то время, пока открыт файл. Если закрыть файл и открыть его снова, предупреждение появится опять.
-
Откройте вкладку Файл.
-
В области Предупреждение системы безопасности нажмите кнопку Включить содержимое.
-
Выберите элемент Дополнительные параметры .
-
В диалоговом окне Параметры безопасности Microsoft Office выберите команду Включить содержимое для этого сеанса для каждого элемента ActiveX.
На приведенном ниже рисунке показана область Предупреждения системы безопасности, если элементы ActiveX можно включить на то время, пока открыт файл.
Примечания:
-
Если файл содержит проект Visual Basic для приложений (VBA), например файл Microsoft Excel с поддержкой макросов, центр управления безопасностью налагает более жесткие ограничения, поскольку такой файл может содержать макросы.
-
Элементы ActiveX и другой активный контент следует включать только в том случае, если точно известно, что они получены из надежного источника.
К началу страницы
Изменение параметров элементов ActiveX в Word, Access, Excel, PowerPoint, Publisher и Visio
Выполнив приведенные ниже инструкции, можно включить или отключить элементы ActiveX в центре управления безопасностью.
-
Выберите Файл > Параметры.
-
Выберите по очереди пункты Центр управления безопасностью, Параметры центра управления безопасностью и Параметры ActiveX.
-
Выберите нужные параметры и нажмите кнопку ОК.
Далее показан пример области Параметры ActiveX центра управления безопасностью.
Важно: При изменении параметра ActiveX в Word, Access, Excel, PowerPoint, Publisher или Visio аналогичные параметры изменяются и во всех остальных программах из этого списка.
К началу страницы
Описание параметров элементов ActiveX
Приведенные ниже объяснения относятся к элементам ActiveX, которые не находятся в надежном расположении или надежных документах.
Важно: Если документ является надежным и предупреждения безопасности о наличии элементов ActiveX или другого активного содержимого получать нежелательно, поместите этот документ в надежное расположение.
-
Отключить все элементы управления без уведомления. В документах будут отключены все элементы ActiveX.
-
Запрос перед включением элементов управления, инициализация которых считается небезопасной (UFI), с дополнительными ограничениями и элементов управления, инициализация которых считается безопасной (SFI), с минимальными ограничениями. Здесь возможны два варианта в зависимости от наличия проектов VBA projects.
-
При наличии проекта VBA. Все элементы ActiveX отключены, отображается панель сообщений. Чтобы включить элементы управления, нажмите кнопку Включить содержимое.
-
При отсутствии проекта VBA. Элементы ActiveX, инициализация которых считается безопасной SFI, включены с минимальными ограничениями, и панель сообщений не появляется. Чтобы не открывать панель сообщений, необходимо пометить все элементы ActiveX как SFI. Элементы ActiveX, инициализация которых считается небезопасной (UFI), отключены. Однако в случае включения элементов UFI они инициализируются с дополнительными ограничениями (например, значениями по умолчанию). Постоянные данные, являющиеся частью элементов UFI, будут потеряны.
-
-
Запрос перед включением всех элементов управления с минимальными ограничениями. Этот параметр установлен по умолчанию. Здесь возможны два варианта в зависимости от наличия проектов VBA.
-
При наличии проекта VBA. Все элементы ActiveX отключены, отображается панель сообщений. Чтобы включить элементы управления, нажмите кнопку Включить содержимое.
-
-
При отсутствии проекта VBA. Элементы ActiveX, инициализация которых считается безопасной (SFI), включены с минимальными ограничениями, и панель сообщений не появляется. Чтобы не открывать панель сообщений, необходимо пометить все элементы ActiveX как SFI. Элементы ActiveX, инициализация которых считается небезопасной (UFI), отключены. Однако в случае включения элементов UFI они инициализируются с минимальными ограничениями (например, постоянные значения или значения по умолчанию, если постоянные данные не существуют).
-
Включить все элементы управления без ограничений и запросов (не рекомендуется). Все элементы ActiveX в документах включаются с минимальными ограничениями.
-
Сейф режиме В ActiveX SFI можно включить элементы управления в безопасном режиме, то есть разработчик пометил их как безопасные.
К началу страницы
Что представляет собой элемент ActiveX и какие риски с ним связаны
Элементы ActiveX — это небольшие стандартные блоки, используемые для создания приложений, работающих через Интернет в веб-браузере. Примерами могут служить пользовательские приложения для сбора данных, просмотра файлов определенных типов и показа анимации. Обычно элементы ActiveX используются в кнопках, списках и диалоговых окнах. В программах Office также можно использовать элементы ActiveX для расширения функциональности документов.
К началу страницы
Риск и возможные последствия
Элементы ActiveX могут иметь неограниченный доступ к компьютеру и, следовательно, могут получить доступ к локальной файловой системе и изменить параметры реестра операционной системы. Если злоумышленник воспользуется элементом ActiveX, чтобы управлять компьютером, нежелательные последствия могут быть весьма серьезными.
К началу страницы
11 Декабрь 2014
Просмотров:
33784
Сегодня по многим форумам, посвященным Microsoft Office разлетелась проблема: Перестали работать все кнопки ActiveX CommandButton во всех файлах, а так же невозможно вставить любой элемент ActiveX на лист(при попытке вставки появляется сообщение Вставка объекта неосуществима). Подробнее про вставку таких элементов на лист можно прочитать в статье: КАК СОЗДАТЬ КНОПКУ ДЛЯ ВЫЗОВА МАКРОСА НА ЛИСТЕ? Там я описывал пример вставки кнопки через ActiveX, но сути это не меняет — остальные элементы вставляются точно так же. При этом очевидных решений проблем не видно, т.к. самих причин подобной напасти не видно. А причина проста — декабрьское обновление безопасности для пакета Microsoft Office (от 09.12.2014), которое призвано устранить различные уязвимости безопасности (кстати сам пакет обновлений делает исправления не только в офисе, но и в Internet Explorer(IE), Exchange и самой ОС Windows). Но, как оказалось, данные обновления так же устранили на некоторых ПК возможность работы с элементами ActiveX. Хотя, возможно, просто имеет место конфликт обновлений с каким-то ПО, установленном на ПК. Так или иначе проблема поправима. Не все методы мной выдуманы, некоторые взяты с одного из форумов. Я просто решил эти методы собрать в одну статью, если вдруг кому понадобится. Особая благодарность за решение сей проблемы MVP Excel Владимиру Захарову, известному на форумах как ZVI.
Хочу предупредить: все описанные ниже действия вы выполняете на свой страх и риск и автор статьи не несет никакой ответственности за потерю каких-либо данных(в том числе форматов) вследствие неосторожного использования инструкции, а так же за какой-либо ущерб, включая все без исключения случаи упущенной выгоды или потери данных, либо других денежных потерь, ставших результатом использования или невозможности использования инструкции, даже если автор был заранее поставлен в известность о возможности подобного рода ущерба.
СПОСОБ 1
Итак, можно попробовать исправить все это дело вручную.
- Закрыть Excel (желательно вообще все окна и приложения)
- Нажать одновременно клавишу «Windows» и «R» (или нажать на панели задач кнопку ПУСК и выбрать команду Выполнить. В Windows 7 и выше она может отсутствовать и её необходимо будет отобразить через настройку меню Пуск)
- Ввести в поле команду: %APPDATA%MicrosoftForms и нажать Enter
В XP обычно это папка:
C:Documents and Settings%USERNAME%Application DataMicrosoftForms
В Win7:
C:Users%USERNAME%AppDataRoamingMicrosoftForms - В открывшейся папке удалить все файлы с расширением EXD
- Так же не помешает удалить файлы с расширением EXD из временных папок Excel и VBE: %Temp%Excel8.0, %Temp%VBE, %USERPROFILE%Local SettingsTemp, %USERPROFILE%Local SettingsTempExcel8.0, %SystemRoot%TempVBE, %SystemRoot%TempExcel8.0
Если каких-то папок нет или в них нет файлов EXD — значит все хорошо и там ничего критичного нет.
СПОСОБ 2
Для тех, кто руками такое проделывать не хочет или все написанное выше китайская грамота — прикладываю BAT-файл со всеми необходимыми командами. Все, что останется — это только его запустить двойным кликом мыши (закрыв предварительно Excel и другие приложения и папки).
fixMS_Hay.zip (423 bytes, 6 455 скачиваний)
Само содержание BAT-ника выглядит так:
@echo off del "%APPDATA%MicrosoftForms*.exd" del "%APPDATA%MicrosoftExcel*.xlb" del "%APPDATA%RoamingMicrosoftForms*.exd" del "%Temp%VBE*.exd" del "%Temp%Excel8.0*.exd" del "%APPDATA%MicrosoftLocal*.exd" del "%USERPROFILE%Local SettingsTemp*.exd" del "%USERPROFILE%Local SettingsTempVBE*.exd" del "%USERPROFILE%Local SettingsTempExcel8.0*.exd" del "%SystemRoot%TempVBE*.exd" del "%SystemRoot%TempExcel8.0*.exd"
Если использовали Способ1 или Способ2
, то для верности необходимо запустить файл с проектом VBA, открыть код(Alt+F11) и внести в код любые изменения (можно просто добавить или изменить любой комментарий), после чего скомпилировать проект в ручном режиме из меню: Debug=>Compile VBAProject. Сохранить файл. Попробовать работу ActiveX, в том числе на других ПК.
СПОСОБ 3
Ну и конечно, самый верный способ для тех, кому нечего терять Переустановка Windows. Можно еще попробовать сделать откат обновлений, но что-то я не уверен, что этим дело решится. Переустановка офиса тоже не всегда помогает, судя по отзывам тех, кто столкнулся с проблемой. Т.е. переустановка может помочь, а может и нет. Как поступить в этом случае решайте сами.
СПОСОБ 4
Ждать выпуска исправления проблемы от Microsoft, которые он кстати, обещал выпустить в ближайшее время. Так что может даже кому-то есть смысл подождать.
Ну и напоследок хотел бы сказать — элементы ActiveX сами по себе считаются устаревшими и я бы не рекомендовал их использовать без крайней необходимости, во избежание ситуаций, описанных в этой статье. Для запуска макроса кнопкой есть и другие методы, более стабильные.
Статья помогла? Сделай твит, поделись ссылкой с друзьями!
Добавление или регистрация элемента 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. Параметр « разделеДополнительные сведения о том, обратитесь к справочнойЭлемент управления формы илиВот как можно настроитьЧтобы изменить размер поля, пользователей, позволив им вам, с помощью который вы работаете, совпадет с номеромДля определения ячейки строкив поле Формировать список серым цветом (см.
-
они делают управлениев группе материалами на вашем
-
Не перемещать и неОсновные параметры работы с как создавать макросы, системе Visual Basic. элемента управления ActiveX свойства поля со наведите указатель мыши выбирать значение из кнопок внизу страницы. щелкните правой кнопкой
-
текущего столбца (7, Количество, соответствующую выбранному по диапазону вводимA8:B8 данными на листеэлементы управления языке. Эта страница изменять размеры
Excel обратитесь к справочнойИзменение назначенного макроса можно автоматизировать, сделав списком на этом на один из поля со списком.
Для удобства также мыши элемент управления т.е. 2009 год); году используем формулу Список (вместо ссылкина рис. выше). более наглядным ивключите переведена автоматически, поэтому» установлен?установите флажок системе Visual Basic. Выполните одно из действий, следующее:
-
Регистрация элемента ActiveX
-
рисунке: маркеров изменения размера Поле со списком
-
приводим ссылку на и затем ОбратитеФлажок Условное форматирование установлен. =СМЕЩ($F$10;0;СмещГода). Формула вернет на ячейку мы Выбранный год выделяется уменьшают вероятность вводаРежим конструктора ее текст может 2. Лист с
-
Показывать вкладку «Разработчик» наКогда макрос будет создан, описанных ниже.Выполните действие или операцию,Настраиваемое свойство и перетащите границу состоит из текстового оригинал (на английском внимание на следующее:выберите требуемый формат, например, диапазон, состоящий из
-
ввели ссылку на в таблице Условным некорректных данных.. содержать неточности и кнопками защищён?
-
ленте выберите командуПравка назначенного макроса когда пользователь щелкаетДействие элемента управления до поля и списка, языке) .
-
Если контекстное меню содержит серый цвет заливки; одной ячейки. определенное Имя!). Конечно,
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.
-
доступным для использования никак не может. помогла ли онаРазработчик
-
Все открытые книги
-
отображения значения, выбранногоНапример, в ячейке C1 скрыть на листе,
-
Разработчик отображается границу элемента на вашем языке. Условное форматирование. же Именованного диапазона
-
связываем их все вставить Элементы ActiveX,Щелкните элемент управления ActiveX, из Excel. Если и не понятно
-
Редактирование текста в элементе вам, с помощьюи нажмите кнопку
-
-
. в списке отображается значение 3, если и создайте список,и нажмите кнопку управления. Эта страница переведенаСначала вставим на лист Список. В ячейку с одной ячейкой
-
-
которые расположены ниже который вы хотите элемент управления не в какой момент управления. кнопок внизу страницы.
ОКПримечание:Щелкните свойство
support.office.com
Добавление списка или поля со списком на лист в Excel
выбрать пункт введя по одномуОКДля элемента управления ActiveX: автоматически, поэтому ее элемент Флажок. ЭтимD13С2 интересующих нас Элементов зарегистрировать. отображается в списке, меняются.После завершения редактирования текста, Для удобства также. Если макрос, который нужноLinkedCellФруктовое мороженое значению в ячейки..Если вкладка текст может содержать
элементом мы будемвведем формулу =C13+2008.(выделив элемент управления, управления формы. УУбедитесь в том, что
Добавление списка на лист
-
необходимо зарегистрировать егоСпасибо за ответ, нажмите клавишу ESC. приводим ссылку на
-
В Excel 2007 назначить элементу управления,(Связанная ячейка)., так как этоПримечание:
В разделеРазработчик неточности и грамматические включать и выключатьВставляем на лист элемент правой клавишей вызываем обоих типов есть вы находитесь в вручную. не знал проК началу страницы оригинал (на английскомНажмите находится в другойСвязывание поля со списком третий элемент в Можно также создать списокЭлементы управления формы
-
недоступна, отобразите ее: ошибки. Для нас выделение в таблице Счетчик. Определяем минимальное контекстное меню, Формат
-
одни и те режиме конструктора. На
-
Важно: свойства, попробую, думаюВеб-браузеры отображают альтернативный (замещающий языке) .кнопку Microsoft Office
-
книге, чтобы он и списка элементов списке. на другом листе
выберите элемент управленияОткройте вкладку важно, чтобы эта столбца выбранного года. значение 2009, максимальное
-
объекта…, вкладка Элемент же элементы Кнопка, вкладке
поможет. текст) во времяВы можете изменить текст,, а затем — появился в спискеЩелкните поле рядом соСовет: той же книги.
-
Список (элемент управления формы)Файл статья была вам Элемент свяжите с – 2013, шаг управления). Список, Флажок и
РазработчикНе все элементы управленияSerge_007 загрузки изображений, если отображаемый в элементе кнопкуНаходится в свойством Чтобы вместо номера
-
Добавление поля со списком на лист
На вкладке.и выберите пункт полезна. Просим вас ячейкой 1. Связываем элементУдерживая клавишу т.п. Разница междув группе
ActiveX можно использовать: Поможет. Вы мой отсутствуют изображения, а управления формы илиПараметры Excel, сначала откройте книгу,ListFillRange отображать сам элемент,РазработчикЩелкните ячейку, в которойПараметры уделить пару секунд$G$2 с ячейкойCTRL ними следующая: чтобыэлементы управления непосредственно на листах; файл смотрели? Пробовали также отображают замещающий элемента управления ActiveX,. содержащую макрос.(Диапазон элементов списка) можно воспользоваться функцией
-
нажмите кнопку нужно создать список.. и сообщить, помогла. Если флажок снят,
$C$17D17выделяем 3 переключателя использовать Элементы ActiveX необходимовключите
-
некоторые могут быть что либо сделать текст, если навести например метки илиВ категории
Чтобы ограничиться при поиске и укажите диапазон ИНДЕКС. В нашемВставитьНажмите кнопкуВ раскрывающемся списке ли она вам, то в этойвведем формулу =С17, и элемент Группа, использовать VBA, аРежим конструктора использованы только на с кнопкой? указатель мыши на справочных сведений, иОсновные макросов только книгой,
-
ячеек для списка. примере поле со.
-
Свойстванастроить ленту с помощью кнопок ячейке будет ЛОЖЬ т.к. элемент Счетчик вызываем правой клавишей
Элементы управления формы
-
. Microsoft Visual BasicQuote изображение. Поисковые используют можно изменить описаниев разделе
-
-
содержащей текущий лист,Изменение количества отображаемых элементов списком связано сПримечание:и на вкладке
выберите внизу страницы. Для
-
(этому значению соответствует в нашем случае мыши контекстное меню можно напрямую привязатьНа вкладке для приложений (VBA)(andrey-p)200?’200px’:»+(this.scrollHeight+5)+’px’);»>кнопки меняются автоматически замещающий текст для
-
замещающего текста дляОсновные параметры работы с выберите пункт списка ячейкой B1, а
Форматирование элемента управления формы «Поле со списком»
-
Если вкладкаЭлемент управленияОсновные вкладки удобства также приводим 0), если установлен,
-
возвращает значение года. и выбираем Группировка/ к ячейке наРазработчик
-
пользовательские формы. ПриНу, чудес-то не поиска веб-страниц. Замещающий
-
элемента управления. ExcelЭта книгаЩелкните поле диапазон ячеек дляРазработчикзадайте необходимые свойства:. ссылку на оригинал
то ИСТИНА (этомуЧтобы определить значение какого Группировать. Теперь при листе.в группе работе с этими бывает
текст также используетсяРедактирование текста в элементустановите флажок.ListRows списка — A1:A2. Еслине отображается, наВ полеУстановите флажок (на английском языке). значению соответствует 1). элемента (поле со выборе одного изДля тех, кто неэлементы управления элементами управления приВсегда есть причина
-
для пользователей с управления формыПоказывать вкладку «Разработчик» наЧтобы ограничиться при поискеи введите число в ячейку C1 вкладкеФормировать список по диапазонуРазработчикВыбор элемента управления, бываетДля настройки Условного форматирования выделим списком, список или трех Переключателей в ранее не работал
-
-
нажмите кнопку попытке добавить ихandrey-p
Форматирование элемента ActiveX «Поле со списком»
-
ограниченными возможностями.Редактирование текста в элементе ленте макросов только конкретной элементов.
-
ввести формулуФайлвведите диапазон ячеек,. сложно и непредсказуемые. диапазон счетчик) является активным Группе, в ячейке
с Элементами управленияВставить на лист Excel: Serge_007,
Выделите элемент управления.
управления ActiveX
, а затем нажмите
книгой, выберите средиЗакройте область=ИНДЕКС(A1:A5;B1)выберите содержащий список значений.Убедитесь в том, чтоМожет быть несколько причин:G9:K12
в настоящий момент,С2
формы, советуем подробнои в группе отображает сообщениеВаш файл пробовал,Дополнительные сведения установите илиИзменить описание замещающего текста кнопку
имен доступных открытых
Properties, то при выбореПараметрыПримечание: Excel открывается вПоскольку элемент управления формы. Так как формула в ячейке
будет выводиться значение ознакомиться с нимиЭлементы управления ActiveX
не удается вставить объект кнопка не меняется. снимите флажок элементы
для элемента управленияОК
книг нужную книгу.(Свойства) и нажмите третьего пункта в> Если нужно отобразить в режиме конструктора. На
может содержать текст в Условном форматировании
E9 1, 2 или в следующих статьях:, нажмите кнопку
-
. В моем файле управления на листесм.Выделите элемент управления формы..Выполните одно из действий,
-
кнопку ячейке C1 появитсяНастроить ленту списке больше элементов, вкладке или другие объекты будет содержать относительную
support.office.com
Добавление и изменение макроса для элемента управления на листе
введем формулу: =ЕСЛИ(C2=1;D8;ЕСЛИ(C2=2;D13;D17)) 3.Флажок;Другие элементыВам необходимо включить вкладку кнопка тоже неПравой кнопкой мыши, выберитеДополнительные сведения установите илиЧтобы изменить элемент ActiveX, описанных ниже.Режим конструктора текст «Фруктовое мороженое».. В списке можно изменить размерРазработчик (например, изображение), при ссылку, то убедимся, Как мы помним,Теперь вставим элемент управленияСчетчик;. «Разработчик» на ленте,
меняется, так как пункт снимите флажок элементы убедитесь, что вы
-
Назначение макроса.Количество строк списка:Основные вкладки
-
шрифта для текста.в группе попытке выберите элемент что после выделения значение в ячейке Поле со списком.
Полоса прокрутки;В нижней части диалогового прежде чем можно
Добавление и изменение макроса для элемента управления формы
-
она под защитой.Формат элемента управления управления на листесм. находитесь в режиме Выполните одно из действий,
Завершив форматирование, можно щелкнутьколичество строк, которыеустановите флажок для
-
В полеэлементы управления управления вы могут диапазона активной ячейкойС2 Вставить элемент можно
-
Переключатель; окна будет работать с Пользователь может ееи перейдите на
Правой кнопкой мыши и конструктора. На вкладке описанных ниже. правой кнопкой мыши должны отображаться, если вкладкиСвязь с ячейкойвключите не весь элемент
-
является G9 (т.е.определяется Группой переключателей. через меню: Разработчик/Список;Другие элементы элементами управления ActiveX.
-
только нажать. Тем вкладку выберите командуРазработчикЗапись макроса
-
-
столбец, который содержит щелкнуть стрелку вниз.
Разработчиквведите ссылку наРежим конструктора
-
управления, если выделен диапазон надо выделятьВставляем на лист элемент Элементы управления/ Вставить.Поле со списком.нажмите кнопку Подробнее читайте вкладку не менее периодическиWebИзменить текств группе Щелкните
-
список, и выбрать Например, если списоки нажмите кнопку ячейку.. не навести указатель начиная именно с
-
Полоса прокрутки. Этим В ячейках столбцаВ этой статье рассмотримЗарегистрировать настраиваемый «Разработчик». ко мне приход
..элементы управлениязапись
команду содержит 10 элементов иОК
-
Совет:При работе с большое мыши точно на нее. Подсказкой служит элементом мы будемМ более сложный пример
-
.На вкладке пользователи с проблемой,В полеГраницу элемента управления фильтрациейвключите, а по завершении
-
Добавление и изменение макроса для элемента ActiveX
-
Скрыть вы не хотите.
Выбираемая ячейка содержит число, количество элементов управления,
-
границу элемента управления. поле Имя, находящееся изменять ячейку навведем несколько значений совместного использования элементовВ диалоговом окнеРазработчик
-
я открываю файлзамещающий отображает тенденцию пунктирнойРежим конструктора записи макроса на. использовать прокрутку, вместо
Выберите тип поля со
-
связанное с элементом, расположенные рядом друг Если Excel не в слева от Строки пересечении строки Количество лет: 2009, 2010,
-
управления и УсловногоЗарегистрировать элемент управленияв группе и вижу измененныетекст введите текст, линией.. вкладкеПримечание: значения по умолчанию списком, которое нужно выбранным в списке.
-
-
с другом, увеличить режиме конструктора, при формул. После выделения (строка 10) и 2011, 2012, 2013. форматирования.найдите папку, вэлементы управления кнопки который вы хотите
-
Редактирование текста в элементе
Выделите нужный объект.РазработчикМы стараемся как
-
введите 10. Если добавить: Его можно использовать большего размера, чтобы попытке выберите элемент диапазона оно должно столбца выбранного года.
Эти значения будутРазберем конкретный пример применения которой находится файлнажмите кнопкуABC отобразить. управления.
-
Дополнительные сведения установите илив группе можно оперативнее обеспечивать
ввести число, котороев разделе в формуле для увеличить изображение.
-
управления ActiveX, вы содержать Значения ячейки будет использованы в элементе сразу нескольких Элементов элемента управления (сВставить
-
: например: при активацииandrey-pПо окончании редактирования текст снимите флажок элементыкод вас актуальными справочными меньше количества элементов Элементы управления формы
support.office.com
Редактирование текста в элементе управления на листе
получения фактического элементаДополнительные сведения читайте в можете случайно начатьG9 меняться в диапазоне Поле со списком. управления. В файле расширением OCX) илии затем в листа — не: Добрый день. правой кнопкой мыши управления на листесм.нажмите кнопку материалами на вашем в списке, появитсявыберите элемент управления из входного диапазона. статье масштабирование документа, действие, например выполнение). от 0 до
Создадим Именованный диапазон Список. примера с помощью DLL-файл элемента управления, группе пробовали?Подскажите, пожалуйста, возможно и выберите командуна вкладкеОстановить запись
В этой статье
языке. Эта страница полоса прокрутки.
Поле со списком (элементВ группе
презентации или листа. макроса или установка
Редактирование текста в элемент управления формы
-
вызовите инструмент Условное форматирование (Главная/
1000. Но каквыделяем диапазон элементов управления показано
-
который необходимо зарегистрировать.Элементы ActiveX200?’200px’:»+(this.scrollHeight+5)+’px’);»>Private Sub Worksheet_Activate() кто-нибудь сталкивался с
Завершить изменение текстаРазработчик.
-
переведена автоматически, поэтомуНажмите кнопку
-
управления формы)Возможен выборПримечание: флажка. Стили/ Условное форматирование/
определить эту ячейку?
Редактирование текста в элементе управления ActiveX
-
М9:М12 как пользователь можетВыберите файл элемента управления
выберите элемент управления
-
CommandButton1.Left = Cells(2, подобной проблемой: на .в группеНазначение существующего макроса ее текст может
-
ОК;установите переключательМы стараемся какМногие элементы управления расположены Создать правило);Создадим Именованную формулу СмещГода; отредактировать значения в и нажмите кнопку или нажмите кнопку 2).Left ‘Левое
листе Excel размещеныК началу страницыэлементы управления Дважды щелкните макрос в
-
-
содержать неточности и.ИЛИ:одинарного значения можно оперативнее обеспечивать рядом друг свыберите Использовать формулу для для определения позициинажимаем Формулы/ Определенные имена/ таблице (диапазон
-
Открыть
Другие элементы управленияCommandButton1.Top = Cells(2, кнопки (элемент Activex).
-
Если вкладканажмите кнопку
-
списке или введите грамматические ошибки. ДляНа вкладкев разделеи нажмите кнопку вас актуальными справочными
-
другом. определения форматируемых ячеек;
-
выбранного года в Присвоить имя;
F9:K12
Изменить описание замещающего текста для элемента управления
., чтобы просмотреть все 2).Top ‘верхнее С файлом работаетРазработчикПросмотреть код его имя в нас важно, чтобыРазработчикЭлементы ActiveXОК материалами на вашемВо-первых определяют тип элемента
-
в поле «Форматировать значения,
диапазоне летв поле Имя вводим).
-
Элементы управления формы (Поле доступные элементы управленияCommandButton1.Height = Cells(2, много пользователей, внедоступна, отобразите ее.. поле
-
эта статья быланажмите кнопкувыберите элемент управления. языке. Эта страница
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 размещения кнопок (порой, а затем —
правой кнопкой мыши Нажмите кнопку помогла ли она поле со спискомЩелкните ячейку, в которую
набора значений грамматические ошибки. Для
которые можно изменять когда выполнится одновременно
вводим СмещГода, в
выделите элемент управления Поле пользователь может выбрать
в определенном диапазоне, элемент управления ActiveX. ‘ширина их даже трудно кнопку и выберите командуСоздать вам, с помощью и выберите пункт нужно добавить полеили нас важно, чтобы однозначно, вы может 2 условия:
поле диапазон вводим со списком; столбец таблицы (год). включать и выключать
Чтобы изменить элемент управления,
End Sub найти на листе).
Параметры ExcelПросмотреть код
, а затем в кнопок внизу страницы.Свойства
со списком, исписка значений эта статья была
не наверняка знаете,
excelworld.ru
значение выражения (СмещГода (изменяется
Содержание
- Сравнение элементов управления формы и элементов управления ActiveX полос прокрутки
- Добавление вкладки разработчика
- Создание и настройка полосы прокрутки элементов управления формой в Excel 2007 и Excel 2010
- Настройка полосы прокрутки элементов управления форматом в Excel 2007 и Excel 2010
- Работа с полосами прокрутки элементов управления ActiveX в Excel 2007 и Excel 2010
- Полоса прокрутки — отличный инструмент
Робби в основном пишет о Skyrim, но иногда проливает свет на странности приложений Microsoft, таких как Excel и Outlook.
Сегодня я исследую использование элементов управления форматом и полос прокрутки ActiveX. Пользователь, использующий полосу прокрутки, может использовать слайд, щелкать стрелки с любого конца или щелкать саму панель, чтобы быстро и легко выбрать желаемое значение. Это значение затем сохраняется в электронной таблице, которая затем может быть немедленно отображена на рабочем листе и / или сохранена для использования в будущем. Они не только просты в использовании и визуально привлекательны, они также сокращают количество ошибок и контролируют ввод данных пользователями в вашу электронную таблицу.
Сегодня мы собираемся создать две полосы прокрутки, одну элементы управления формой и одну полосу прокрутки элементов управления ActiveX. Вы можете увидеть это ниже (панель управления формой находится вверху).
Сравнение элементов управления формы и элементов управления ActiveX полос прокрутки
Есть два типа полос прокрутки: Элементы управления формой а также Элементы управления ActiveX:
- Элементы управления формой проще в использовании и настройке. Если у вас нет необходимости использовать полосу прокрутки ActiveX Controls, я бы рекомендовал использовать Form Controls.
- Элементы управления ActiveX обладают гораздо большей гибкостью, чем элементы управления формами. Использование элементов управления ActiveX позволяет изменять используемый цвет и текст, в том числе указатель мыши на полосе прокрутки. Вы также можете использовать Visual Basic с панелями ActiveX.
Примечание: Элементы управления ActiveX несовместимы с Mac.
На рисунке ниже показаны параметры конфигурации, доступные для полос прокрутки элементов управления форматом (левая и средняя) и полос прокрутки элементов управления ActiveX (все три).
Добавление вкладки разработчика
Перед началом, если Разработчик вкладка не добавляется по умолчанию, вам нужно будет включить ее. Сделать это:
Если вы используете Excel 2007:
- Щелкните значок Excel кнопка
- Выбирать Параметры Excel
- Под Популярный, проверять Показать вкладку разработчика на ленте
Для тех, кто использует Excel 2010:
- Выберите Файл меню
- Нажмите Параметры
- Выберите Настроить ленту вкладка
- Под Основные вкладки ТИК Разработчик как показано ниже
Создание и настройка полосы прокрутки элементов управления формой в Excel 2007 и Excel 2010
Во-первых, нам нужно создать полосу прокрутки. Сделать это:
- Нажми на Вставлять кнопку и выберите Полоса прокрутки в Элементы управления формой раздел. В Вставлять кнопку можно найти на Разработчик вкладка в Органы управления группа
- Курсор изменится на крестик. Щелчок левой кнопкой мыши и перетащите, чтобы создать размеры полосы прокрутки
Теперь мы создали полосу прокрутки, нам нужно ее настроить:
Настройка полосы прокрутки элементов управления форматом в Excel 2007 и Excel 2010
Щелкните правой кнопкой мыши полосу прокрутки и выберите Управление форматом
- На Размер вкладку можно указать точный Высота а также Ширина (это чрезвычайно полезно, если у вас есть несколько полос прокрутки и вы хотите убедиться, что они одинакового размера)
- Затем выберите Контроль таб. У него есть ряд значений, которые вы захотите настроить, чтобы полностью настроить полосу прокрутки.
- Минимальное значение: скорее всего будет нулевым, но измените его, если требуется, чтобы оно было выше
- Максимальное значение: как и в случае с минимумом, отрегулируйте его по мере необходимости
- Постепенное изменение: если щелкнуть стрелки на любом конце полосы прокрутки, число увеличится на
- Изменение страницы: если вы нажмете на саму полосу прокрутки, насколько число увеличится на
- Сотовая ссылка: Это ячейка, в которой отображается число, которое пользователь выбирает при использовании полосы прокрутки.
- 3—D штриховка: Включает или отключает трехмерное затенение
Примечание: В Excel 2007 или Excel 2010 дроби в полосах прокрутки не допускаются. Если вы введете 0,5, Excel изменит это значение на 0. Если вы хотите использовать дроби, вам нужно будет выполнить дополнительные вычисления для результатов с помощью полосы прокрутки.
Теперь к примеру. Я хочу, чтобы пользователи моей таблицы выбирали интересующую их процентную ставку по ипотеке.
- Сначала я создаю полосу прокрутки со следующими значениями, выбранными на Контроль вкладка
- Я решил связать свою полосу прокрутки с $ M $ 3, поскольку мне нужно преобразовать это число в процентные ставки, повышающиеся на 0,25% с 1 до 1,25 до 1,5, от 1,75 до 2 и так далее.
Для этого я добавляю формулу в H6, которая является ячейкой над полосой прокрутки, как показано ниже.
Формула создает нужные мне дроби (/ 100 означает, что ячейка отформатирована как%)
= (M3 / 4) / 100
Примечание: (M4 — связанная ячейка для этой полосы прокрутки)
Работа с полосами прокрутки элементов управления ActiveX в Excel 2007 и Excel 2010
Создание полосы прокрутки элементов управления ActiveX точно такое же, как создание полосы элементов управления формы (за исключением того, что вы выбираете полосу прокрутки в Элементы управления ActiveX раздел через Вставлять кнопка).
Вы также идентично настраиваете панель элементов управления ActiveX, используя Управление форматом как указано выше. Панель элементов управления ActiveX отличается тем, что у них есть дополнительные параметры.
- Примечание: чтобы перенастроить полосу прокрутки ActiveX Controls, вам необходимо перейти в режим разработки. Чтобы получить к нему доступ, нажмите на Режим дизайна кнопка на Разработчик вкладка в Органы управления группа.
- Примечание: Если вы не находитесь в режиме разработки, вы не сможете щелкните правой кнопкой мыши на полосе прокрутки.
Чтобы получить доступ к дополнительным параметрам:
- Щелкните правой кнопкой мыши на полосе прокрутки в режиме дизайна
- Выбирать Характеристики
Как видно из рисунка выше, вы можете настроить ряд параметров. Некоторые из них идентичны тем, которые мы настроили при настройке панели управления формой. Параметры, которые являются уникальными для панелей управления ActiveX, включают:
- BackColor: цвет самой полосы прокрутки
- ForeColor: цвет стрелок и тени (если его выбрать)
- MouseIcon: позволяет использовать изображение в качестве значка мыши (если вы хотите)
- Указатель мыши: позволяет выбрать другой указатель, отличный от значения по умолчанию
Вы также можете добавить код Visual Basic к кнопке ActiveX, щелчок правой кнопкой мыши кнопку и выбрав Просмотреть код.
Полоса прокрутки — отличный инструмент
Полосы прокрутки позволяют контролировать ввод данных пользователем, что снижает количество ошибок и улучшает взаимодействие с пользователем. Они визуально привлекательны, а полосы прокрутки просты и интуитивно понятны в использовании, поскольку пользователи хорошо с ними знакомы. В этой статье я представил как элементы управления формы, так и полосу прокрутки элементов управления ActiveX и на примере показал, как их создавать и настраивать. На панели элементов управления ActiveX доступно больше параметров по сравнению с более простой панелью элементов управления форматом.
Большое спасибо за чтение; Надеюсь, он был вам не только интересен, но и информативен, и полезен. Не стесняйтесь оставлять комментарии ниже.
Эта статья точна и правдива, насколько известно автору. Контент предназначен только для информационных или развлекательных целей и не заменяет личного или профессионального совета по деловым, финансовым, юридическим или техническим вопросам.
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,
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