Visual basic excel выпадающий список

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

Элемент управления ComboBox на пользовательской форме

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

ComboBox представляет из себя комбинацию двух элементов управления: текстового поля (TextBox) и списка (ListBox), поэтому его еще называют «комбинированным списком» или «полем со списком». Также ComboBox сочетает в себе свойства этих двух элементов управления.

Изначально комбинированный список прорисовывается на форме в виде текстового поля с кнопкой для отображения раскрывающегося списка. Далее по тексту будем использовать слово «поле» в значении текстового поля в составе элемента управления ComboBox, а словосочетание «раскрывающийся список» – в значении списка в составе элемента управления ComboBox.

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

Элемент управления ComboBox незаменим при больших списках. При списках из нескольких позиций его можно заменить на ListBox, который отображает позиции для выбора сразу после загрузки формы, не требуя дополнительных действий от пользователя.

Свойства поля со списком

Свойство Описание
AutoSize Автоподбор размера комбинированного поля. True – размер автоматически подстраивается под длину выбранной или введенной строки. False – размер элемента управления определяется свойствами Width и Height.
AutoTab Включение автоматической табуляции – передачи фокуса следующему элементу управления при достижении максимального числа символов при значениях свойства MaxLenght > 0. True – автоматическая табуляция включена, False – выключена.
ColumnCount Указывает количество столбцов в раскрывающемся списке. Значение по умолчанию = 1.
ColumnHeads Добавляет строку заголовков в раскрывающийся список. True – заголовки столбцов включены, False – заголовки столбцов выключены. Значение по умолчанию = False.
ColumnWidths Ширина столбцов в раскрывающемся списке. Значения для нескольких столбцов указываются в одну строку через точку с запятой (;).
ControlSource Ссылка на ячейку для ее привязки к элементу управления ComboBox.
ControlTipText Текст всплывающей подсказки при наведении курсора на элемент управления.
Enabled Доступ пользователя к полю и раскрывающемуся списку. True – доступ разрешен, False – доступ запрещен*. Значение по умолчанию = True.
Font Шрифт, начертание и размер текста в поле.
Height Высота элемента управления ComboBox.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края комбинированного списка.
List Позволяет заполнить ComboBox данными из одномерного или двухмерного массива, а также обращаться к отдельным элементам раскрывающегося списка по индексам для записи и чтения.
ListIndex Номер выбранной пользователем строки в раскрывающемся списке. Нумерация начинается с нуля. Если ничего не выбрано, ListIndex = -1.
ListRows Количество видимых строк в раскрытом списке. Если общее количество строк больше ListRows, появляется полоса прокрутки. Значение по умолчанию = 8.
Locked Запрет на отображение раскрывающегося списка, ввод и редактирование данных в поле. True – ввод и редактирование запрещены**, False – ввод и редактирование разрешены. Значение по умолчанию = False.
MatchRequired Задает проверку вводимых в поле строк с элементами списка. True – проверка включена (допускается ввод только строк, совпадающих с элементами списка), False – проверка выключена (допускается ввод любых строк). Значение по умолчанию = False.
MaxLenght Максимальная длина строки в поле. Значение по умолчанию = 0, что означает – ограничений нет.
RowSource Источник строк для раскрывающегося списка (адрес диапазона на рабочем листе Excel).
TabIndex Целое число, определяющее позицию элемента управления в очереди на получение фокуса при табуляции. Отсчет начинается с 0.
Text Текстовое содержимое (значение) поля (=Value).
TextAlign Выравнивание текста в поле: 1 (fmTextAlignLeft) – по левому краю, 2 (fmTextAlignCenter) – по центру, 3 (fmTextAlignRight) – по правому краю.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края комбинированного списка.
Value Текстовое содержимое (значение) поля (=Text).
Visible Видимость поля со списком. True – ComboBox отображается на пользовательской форме, False – ComboBox скрыт.
Width Ширина элемента управления.

* При Enabled в значении False пользователь не может раскрывать список, а также вводить или редактировать данные в поле.
** Для элемента управления ComboBox действие свойства Locked в значении True аналогично действию свойства Enabled в значении False.

В таблице перечислены только основные, часто используемые свойства поля со списком. Еще больше доступных свойств отображено в окне Properties элемента управления ComboBox, а все методы, события и свойства – в окне Object Browser.

Вызывается Object Browser нажатием клавиши «F2». Слева выберите объект ComboBox, а справа смотрите его методы, события и свойства.

Свойства BackColor, BackStyle, BorderColor, BorderStyle отвечают за внешнее оформление комбинированного списка и его границ. Попробуйте выбирать доступные значения этих свойств в окне Properties, наблюдая за изменениями внешнего вида элемента управления ComboBox на проекте пользовательской формы.

Способы заполнения ComboBox

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

With UserForm1.ComboBox1

  .AddItem «Элемент 1»

  .AddItem «Элемент 2»

  .AddItem «Элемент 3»

End With

Используйте свойство List, чтобы скопировать одномерный массив значений в элемент управления ComboBox:

UserForm1.ComboBox1.List = Array(«Строка 1», _

«Строка 2», «Строка 3», «Строка 4», «Строка 5»)

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

Используйте свойство RowSource, чтобы загрузить в ComboBox значения из диапазона ячеек рабочего листа:

UserForm1.ComboBox1.RowSource = «Лист5!B1:B15»

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

With UserForm1.ComboBox1

  ‘Указываем количество столбцов

  .ColumnCount = 5

  .RowSource = «‘Таблица с данными’!A1:E20»

End With

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

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

Привязка поля со списком к ячейке

Чтобы привязать комбинированный список к ячейке на рабочем листе Excel, необходимо свойству ControlSource присвоить адрес ячейки. Это можно сделать непосредственно в окне Properties элемента управления ComboBox или в коде VBA:

UserForm1.ComboBox1.ControlSource = "Лист1!B2"

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

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

Чтобы протестировать результаты привязки ячейки к полю со списком ComboBox1, разместите на пользовательской форме UserForm1 еще какой-нибудь элемент управления и запустите следующий код VBA Excel:

Sub Test()

With UserForm1.ComboBox1

  ‘Заполняем список ComboBox1 данными

  .List = Array(«Красный», «Оранжевый», «Желтый», _

  «Зеленый», «Голубой», «Синий», «Фиолетовый»)

  ‘Привязываем ComboBox1 к ячейке «A1»

  .ControlSource = «A1»

  ‘Открываем форму в немодальном окне

End With

  UserForm1.Show 0

End Sub

В результате работы кода пользовательская форма откроется в немодальном окне со значением в поле, скопированном из ячейки «A1» активного листа. Немодальное окно формы позволит редактировать ячейку «A1», не закрывая форму.

Меняйте значение ячейки «A1», нажимайте клавишу «Tab» или «Enter», поле комбинированного списка примет значение ячейки. Меняйте значение поля ComboBox1 с помощью клавиатуры или выбирайте из раскрывающегося списка, нажимайте клавишу «Tab» или «Enter», ячейка «A1» примет значение поля со списком.

Дополнительный элемент управления на форме нужен для передачи ему фокуса нажатием клавиши «Tab» или «Enter», чтобы завершить ввод значения в поле ComboBox1. Иначе новое значение поля будет передано в ячейку «A1» только при закрытии формы.

Значение ComboBox по умолчанию

В раскрывающийся список элемента управления ComboBox1 загружены названия семи основных цветов:

Private Sub UserForm_Initialize()

With Me.ComboBox1

  .List = Array(«Красный», «Оранжевый», «Желтый», _

  «Зеленый», «Голубой», «Синий», «Фиолетовый»)

  ‘Сюда добавляем код вставки значения по умолчанию

End With

End Sub

Есть несколько вариантов сделать так, чтобы при открытии пользовательской формы в поле ComboBox1 было отображено значение по умолчанию. Код следует вставлять перед строкой «End With».

‘Вариант 1 (произвольная строка)

.Value = «Моя строка по умолчанию»

‘или

.Value = «Синий»

‘Вариант 2 (произвольная строка)

.ControlSource = «A1»

Range(«A1») = «Моя строка по умолчанию»

‘или

.ControlSource = «A1»

Range(«A1») = «Желтый»

‘Вариант 3 (строка из списка)

.ListIndex = 0 ‘Красный

‘или

.ListIndex = 3 ‘Зеленый

Кроме значения по умолчанию, в свойства комбинированного списка можно добавить текст всплывающей подсказки, который будет отображаться при наведении на ComboBox курсора:

UserForm1.ComboBox1.ControlTipText = "Выберите значение из списка"

Извлечение информации из ComboBox

Первоначально элемент управления ComboBox открывается с пустым полем или значением по умолчанию. Свойства Value и Text в этом случае возвращают пустую строку или текст по умолчанию.

Если пользователь выбрал новое значение из раскрывающегося списка или ввел его с клавиатуры, оно перезапишет значения свойств Value и Text. Из этих свойств мы с помощью кода VBA Excel извлекаем информацию, выбранную или введенную пользователем:

Dim myTxt As String

myTxt = UserForm1.ComboBox1.Value

‘или

myTxt = UserForm1.ComboBox1.Text

Вторую строку кода можно записать myTxt = UserForm1.ComboBox1, так как Value является свойством поля со списком по умолчанию.

Если вас интересует, как извлечь значение из многостолбцового раскрывающегося списка, смотрите об этом в статье с описанием элемента управления ListBox. Извлечение данных из комбинированного поля аналогично извлечению данных из ListBox. Знакомясь со статьей, следует учесть, что у ComboBox отсутствует многострочный выбор.

Иногда перед загрузкой в ComboBox требуется отобрать уникальные элементы из имеющегося списка. Смотрите, как это сделать с помощью объектов Collection и Dictionary.

In this Article

  • Create a ComboBox in Excel Worksheet
  • Populate a ComboBox in VBA code
  • Populate a ComboBox from a Cells Range
  • Get a Selected Item of a ComboBox in VBA
  • Clear a ComboBox
  • Use a ComboBox in a Userform

This tutorial will demonstrate how to work with ComboBoxes in VBA.

ComboBoxes allow users to select an option from a drop-down menu list. ComboBoxes can be created in VBA UserForms or with an Excel worksheet. In this tutorial, you will learn how to create and manipulate ComboBoxes in VBA and in Excel worksheets.

If you want to learn how to create a Listbox, click here: VBA Listbox

If you want to learn how to create a Checkbox, click here: VBA Checkbox

Create a ComboBox in Excel Worksheet

In order to insert a ComboBox in the Worksheet, you need to go to the Developer tab, click Insert and under ActiveX Controls choose Combo Box:

vba insert combobox

Image 1. Insert a ComboBox in the Worksheet

When you select the ComboBox which you inserted, you can click on Properties under the Developer tab:

vba combobox properties

Image 2. Change ComboBox Properties

Here you can set different properties of the ComboBox. To start, we changed the attribute Name to cmbComboBox. Now, we can use the ComboBox with this name in VBA code.

Populate a ComboBox in VBA code

First, we need to populate the ComboBox with values. In most cases, a ComboBox needs to be populated when the Workbook is opened. Because of this, we need to put a code for populating the ComboBox in object Workbook, procedure Open. This procedure is executed every time a user opens the Workbook. Here is the code:

With Sheet1.cmbComboBox

    .AddItem "John"
    .AddItem "Michael"
    .AddItem "Jennifer"
    .AddItem "Lilly"
    .AddItem "Robert"

End With

When you click on the drop-down menu, you will get 5 names to choose from (John, Michael, Jennifer, Lilly and Robert):

vba combobox populate

Image 3. Populate the ComboBox in VBA

Populate a ComboBox from a Cells Range

Another possible way to populate a ComboBox is to let a user do it. A ComboBox can be linked to the cells range. In this approach, every time a user enters a new value in the cells range, the ComboBox will update with that value.

If you want to enable this, you have to go to the Properties of the ComboBox and set the attribute ListFillRange to the cells range (in our case E2:E5):

vba populate combobox from cells range

Image 4. Populate the ComboBox from the cells range

We linked our ComboBox with the range E2:E5, where we put names we want (Nathan, Harry, George, Roberta). As a result, the ComboBox is now populated with these names:

vba populated combobox

Image 5. Populated ComboBox from the cells range

Get a Selected Item of a ComboBox in VBA

The purpose of a ComboBox is to get a users choice. In order to retrieve a users choice, you need to use this code:

Dim strSelectedItem As Variant

strSelectedItem = Sheet1.cmbComboBox.Value

The users selection is in the attribute Value of Sheet1.cmbComboBox object. This value is assigned to the variable strSelectedItem:

vba combobox get selected value

Image 6. Get a selected value from the ComboBox in VBA

We selected Julia in the ComboBox and executed the procedure. As you can see in Image 5, the value of the strSelectedItem is Julia, which is the value we selected. Now you can process this variable further in the code.

Clear a ComboBox

If you want to clear a ComboBox in VBA, you need to use Clear method of Sheet1.lstComboBox object. It will delete all the items from the ComboBox. Here is the code:

Sheet1.cmbComboBox.Clear

Notice that the Clear method does not delete the attribute ListFillRange, so it must be removed from the properties of the ComboBox beforehand.

When we execute the code, we get the empty ComboBox:

vba clear combobox

Image 7. Clear the ComboBox

Use a ComboBox in a Userform

As we mentioned, Combobox is most often used in Userforms. To explain how you can do it, we will first insert an Userform. In VBA editor, right-click on Module name, click on Insert and choose UserForm:

vba combobox insert userform

Image 8. Insert a Userform

To display controls for inserting, you need to enable the Toolbox. To do this, click on the Toolbox icon in the toolbar. After that, you will get the windows with all the controls available. You can click on ComboBox to create it in the Userform.

vba combobox insert in userform

Image 9. Insert a ComboBox in the Userform

We will name the ComboBox cmbComboBox. In order to populate it with values, we need to put the following code into the method Initialize of the object UserForm:

Private Sub UserForm_Initialize()

    With UserForm1.cmbComboBox

        .AddItem "John"
        .AddItem "Michael"
        .AddItem "Jennifer"
        .AddItem "Lilly"
        .AddItem "Robert"

    End With

End Sub

This code triggers every time a user runs the Userform and populates the Combobox with these 5 names:

vba combobox in userform

Image 10. The ComboBox with values in the Userform

If you want to get selected value from the ComboBox, you need to use the same logic for the Combobox in a Worksheet, which is explained earlier in the article.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA For Excel's Form Control Combo Boxes

You’re VBA Combo Box Cheat Sheet

In this post I am going to share everything I know about using VBA with an Excel Form Control Combo Box (aka drop down).  Most of the code is very self-explanatory so I will not write much of a description.  However, some of the syntax can be a little tricky so pay close attention to how the code is structured.  Please feel free to post comments if I missed an area or you have any questions!  Enjoy :)

Creating & Sizing/Positioning A Combo Box

Sub ComboBox_Create()
‘PURPOSE: Create a form control combo box and position/size it

Dim Cell As Range
Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

‘Create
  sht.DropDowns.Add(0, 0, 100, 15).Name = «Combo Box 1»

‘Create & Dimension to a Specific Cell
  Set Cell = Range(«B5»)

    With Cell
    sht.DropDowns.Add(.Left, .Top, .Width, .Height).Name = «Combo Box 2»
  End With

‘Create & Dimension to a Specific Cell Range
  Set Cell = Range(«B8:D8»)

    With Cell
    sht.DropDowns.Add(.Left, .Top, .Width, .Height).Name = «Combo Box 3»
  End With

End Sub

Deleting A Combo Box

Sub ComboBox_Delete()
‘PURPOSE: Delete a form control combo box

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

sht.Shapes(«Combo Box 1»).Delete

End Sub

Adding Values To A Combo Box

Sub ComboBox_InputRange()
‘PURPOSE: Add values to your drop down list

Dim Cell As Range
Dim sht As Worksheet
Dim myArray As Variant
Dim myDropDown As Shape

Set sht = ThisWorkbook.Worksheets(«Sheet1»)
Set myDropDown = sht.Shapes(«Combo Box 1»)
myArray = Array(«Q1», «Q2», «Q3», «Q4»)

‘Based on data in a range (not linked)
  MyDropDown.ControlFormat.List = sht.Range(«A1:A4»).Value

  ‘Linked to data in a range (automatically changes based on current cell values)
  myDropDown.ControlFormat.ListFillRange = «A1:A4»

  ‘Based on Array values (written out)
  MyDropDown.ControlFormat.List = _
   Array(«Q1», «Q2», «Q3», «Q4»)

‘Based on Array values (variable)
  myDropDown.OLEFormat.Object.List = myArray

  ‘Add one by one
  With myDropDown.ControlFormat
    .AddItem «Q1»
    .AddItem «Q2»
    .AddItem «Q3»
    .AddItem «Q4»
  End With

End Sub

Overriding Values In The Drop Down List

Sub ComboBox_ReplaceValue()
‘PURPOSE: Replace value of the third item in the drop down list

Worksheets(«Sheet1»).Shapes(«Combo Box 1»).ControlFormat.List(3) = «FY»

End Sub

Removing Values From The Drop Down List

Sub ComboBox_RemoveValues()
‘PURPOSE: Remove a value(s) from the drop down list

Dim Cell As Range
Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

‘Remove A Single Item
  sht.Shapes(«Combo Box 1»).ControlFormat.RemoveItem 2

‘Remove All Items
  sht.Shapes(«Combo Box 1»).ControlFormat.RemoveAllItems

End Sub

Determine Current Selected Value From The Drop Down List

Sub ComboBox_GetSelection()
‘PURPOSE: Determine current selected value in ComboBox

Dim sht As Worksheet
Dim myDropDown As Shape

Set sht = ThisWorkbook.Worksheets(«Sheet1»)
Set myDropDown = sht.Shapes(«Combo Box 1»)

With myDropDown.ControlFormat
  MsgBox «Item Number: » & .Value & vbNewLine & «Item Name: » & .List(.Value)
End With

End Sub

Select A Value From The Drop Down List

Sub ComboBox_SelectValue()
‘PURPOSE: Automatically select a value from the drop down list

Dim Cell As Range
Dim sht As Worksheet
Dim Found As Boolean
Dim SetTo As String
Dim x As Long

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

‘Select First List Item
  sht.Shapes(«Combo Box 1»).ControlFormat.ListIndex = 3

  ‘Select Item based on list Name/Value
  SetTo = «Q2»

    With sht.Shapes(«Combo Box 1»).ControlFormat
    For x = 1 To .ListCount
      If .List(x) = SetTo Then
        Found = True
        Exit For
    Next x

      If Found = True Then .ListIndex = x
  End With

End Sub

Link User’s Selection To A Cell (Outputs Numerical List Position)

Sub ComboBox_CellLink()
‘PURPOSE: Output the selection’s list position to a specific cell

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

sht.Shapes(«Combo Box 1»).ControlFormat.LinkedCell = «$A$1»

End Sub

Adjust Drop Down Lines For A Combo Box

Sub ComboBox_DropDownLines()
‘PURPOSE: Set how many drop down lines are visible per scroll

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

sht.Shapes(«Combo Box 1»).ControlFormat.DropDownLines = 12

End Sub

Toggle On/Off 3D Shading

Sub ComboBox_3DShading()
‘PURPOSE: Turn 3D shading on or off

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

‘Turn 3D Shading On
  sht.Shapes(«Combo Box 1»).OLEFormat.Object.Display3DShading = True

‘Turn 3D Shading Off
  sht.Shapes(«Combo Box 1»).OLEFormat.Object.Display3DShading = False

End Sub

Assigning A Macro To A Combo Box

Sub ComboBox_AssignMacro()
‘PURPOSE: Assign a macro to be triggered when drop down is changed

Dim sht As Worksheet

Set sht = ThisWorkbook.Worksheets(«Sheet1»)

sht.Shapes(«Combo Box 1»).OnAction = «Macro1»

End Sub

Any Others?

If I’ve missed any VBA functionalities please leave a comment in the comments section below so I can continue to grow this list of combo box code!  I look forward to hearing your thoughts.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

Excel VBA ComboBox

Combo Box is the UserForm feature in VBA. They are different from the text boxes as text boxes used to contain only text. We allow the user to input any data, but by using combo boxes, we limit users to the desired response type. Thus, the data is in an orderly fashion. It is similar to the list data validation in Excel.

Combo Box can be compared to a dropdown list in Excel in worksheets. We used data validation to provide a dropdown. But in VBA, a UserForm feature provides a dropdown in any UserForm. But, if we want to use a combo box in Excel, we can access it from the “Developer” section. From there, we can create combo boxes for individual or multiple cells.

Combo Box is very similar to the dropdown list we have in an excel worksheet. With the combo box, we can store predetermined values so that users make the selection from the list available from the combo box. The combo box is generally used with UserForms to get the users’ input.

UserForms are useful but having other tools on the user form is what makes the user form so special. One of the tools that we often use as a tool for UserForm is “Combo Box.”

Table of contents
  • Excel VBA ComboBox
    • Top 2 Ways of Creating a VBA ComboBox
      • #1 – Using Direct Coding
      • #2 – Using UserForm
    • Things to Remember
    • Recommended Articles

VBA-Combo-Box

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA ComboBox (wallstreetmojo.com)

Top 2 Ways of Creating a VBA ComboBox

You can download this VBA Combo Box Excel Template here – VBA Combo Box Excel Template

#1 – Using Direct Coding

First, we will see how to use Combo Box with the worksheetCombo Box in Excel is a type of data validation tool that can create a dropdown list for the user to select from the pre-determined list. It is a form control which is available in the insert tab of the developer’s tab.read more. Next, open any worksheets in the Excel workbook, and go to the Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more. Under this tab, we have a tool called “Insert.” Click on this, and under this, we have two options Active X Controls and Form Controls in excelExcel Form Controls are objects which can be inserted at any place in the worksheet to work with data and handle the data as specified. These controls are compatible with excel and can create a drop-down list in excel, list boxes, spinners, checkboxes, scroll bars.read more.

VBA Combo box Example 1

From “Active X Controls,” choose “Combo Box.”

VBA Combo box Example 1-1

Now you can draw this object on any of the worksheets.

VBA Combo box Example 1-2

Right-click on the combo box and choose the “Properties” option.

VBA Combo box Example 1-3

When you choose properties, it will open up a huge list of combo box properties.

VBA Combo box Example 1-4

We will give a list of department names for this combo box, so change the name property of the combo box to “DeptComboBox.”

VBA Combo box Example 1-5

This combo box will be referred to by the name “DeptComboBox.” We need to give pre-determined department names, so here I have a list of department names.

VBA Combo box Example 1-6

Now we need to add these values to the combo box list. We can do this in two ways, through coding or name managerThe name manager in Excel is used to create, edit, and delete named ranges. For example, we sometimes use names instead of giving cell references. By using the name manager, we can create a new reference, edit it, or delete it.read more.

VBA Combo box Example 1-7

Double click on the combo box, which will take you to the VBA macroVBA Macros are the lines of code that instruct the excel to do specific tasks, i.e., once the code is written in Visual Basic Editor (VBE), the user can quickly execute the same task at any time in the workbook. It thus eliminates the repetitive, monotonous tasks and automates the process.read more procedure.

VBA Combo box Example 1-8

But we need to see these department names when the workbook opens up, so double click on “ThisWorkbook.”

VBA Combo box Example 1-9

From the dropdown list, choose “Workbook.”

VBA Combo box Example 1-10

From the options, choose “Open.”

VBA Combo box Example 1-11

Now it will create a blank like the one below.

VBA Combo box Example 1-12

Inside this macro, enter the below code.

Code:

Private Sub Workbook_Open()

With Worksheets("Sheet1").DeptComboBox
.AddItem "Finance"
.AddItem "Marketing"
.AddItem "Merchandising"
.AddItem "Operations"
.AddItem "Audit"
.AddItem "Client Servicing"
End With

End Sub

VBA Combo box Example 1-13

Now save and close the workbook. When you reopen the workbook, we can see its department names.

VBA Combo box Example 1-7

#2 – Using UserForm

Another way to add values to the combo box is using the UserForm. First, give a name to cells as “Department.”

VBA Combo box Example 1-14

Next, enter Visual Basic EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more and insert “UserForm” from the “INSERT” option.

VBA Combo box Example 1-15

Now, it has created the new UserForm.

VBA Combo box Example 1-16

Next to the UserForm, we can see “Toolbox” from this toolbox. Then, finally, we can insert “ComboBox.”

VBA Combo box Example 1-17

Now, the combo box is embedded in the UserForm. To open the properties option, select the combo box and press the F4 key to open the properties window.

VBA Combo box Example 1-18

Scroll down the “Properties” tab and choose “RowSource.”

VBA Combo box Example 1-19

For this “RowSource,” enter the name we had given to department name cells.

rowsource Example 1-20

Now, this combo box holds the reference of the name “Department.”

Now, run the UserForm by using the “Run” button.

run userform Example 1-21

Now, we can see a list of department names in the combo box on the UserForm.

VBA Combo box Example 1-22

Practically UserForm is associated with a combo box, text box, and many other tools. Therefore, we will create a simple data entry UserForm with a text box and combo box.

Create a UserForm like the one below.

create userform Example 1-23

Create two “Command” buttons.

command button Example 1-24

Double click on the “SUBMIT” button. It will open up below the macro.

macro code Example 1-25

Inside this macro, add the below code.

Code:

Private Sub CommandButton1_Click()

Dim LR As Long

LR = Cells(Rows.Count, 1).End(xlUp).Row + 1

Cells(LR, 1).Value = TextBox1.Value
Cells(LR, 2).Value = ComboBox1.Value

End Sub

Submit button Example 1-26

Now, double-click the “CANCEL” button and add the code below.

Cancel button Example 1-27

Now, in the worksheet, create a template like the one below.

Excel worksheet Example 1-28

Now, run the UserForm. It will open up like this.

created userform Example 1-29

Enter the employee name and pick the department name from the combo list.

department Example 1-30

Click on the “SUBMIT” button and see the magic.

VBA Combo box Example 1-31

We got the values entered in the table format we have created.

Things to Remember

  • The COMBO BOX has its properties as well.
  • Adding values to the list comes in two ways. One is a coding way, and another is a range name reference.
  • The COMBO BOX is usually part of the UserForm.

Recommended Articles

This article has been a guide to VBA Combo Box. Here, we discuss how to insert and use a combo box using VBA coding in Excel along with the downloadable template. Below you can find some useful Excel VBA articles: –

  • List Box in Excel
  • Name Box in Excel
  • VBA InputBox
  • Examples of Checkbox in Excel

Ребят, а может мне кто-нибудь подскажет вариант реализации? Задача у меня такая: есть файл с адресами: Город, Улица, Дом — это столбцы. Файл для каждого региона свой, и он динамичный лежит в общем справочнике. Мы работаем с другим файлом, в который вставляется нужный листик, в зависимости от того, какой регион его открывает. Это я написала. Так вот… теперь надо, чтобы на другом листочке в столбцах Город/улица/дом, выходили выпадающие списки, причём для определённого города, только его улицы, а для улиц дома… При этом не должно быть пустых и улицы уникальны.

Я придумала два варианта реализации… Но они оба не отличаются особым успехом.

Первый: почти без VBA

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

далее, так как у меня есть список Город-Улица (на адресном листе), с помощью формулы смещения и поиска позиции нахожу улицы только этого города.(минус этого такой, что эта формула в именах постоянно почему-то (!) сбивается…)

Далее аналогично, этой же формулой нахожу дома для улиц.

Второй способ — не осуществила до конца, так как ступор… Создала уникальные города на отдельном листе в строку… Далее создала под каждым городом его улицы — так же уникальные… А вот теперь надо через ДВССЫЛ через VBA создать столько имён, сколько у меня вышло городов…. вообщем как это сделать…. если это реально…

Если есть другой вариант решения очень жду!!

Заранее спасибо

based on examples above and examples found on other sites, I created a generic procedure and some examples.

'Simple helper procedure to create a dropdown in a cell based on a list of values in a range
'ValueSheetName : the name of the sheet containing the value range
'ValueRangeString : the range on the sheet with name ValueSheetName containing the values for the dropdown
'CreateOnSheetName : the name of the sheet where the dropdown needs to be created
'CreateInRangeString : the range where the dropdown needs to be created
'FieldName As String : a name of the dropdown, will be used in the inputMessage and ErrorMessage
'See example below ExampleCreateDropDown
Public Sub CreateDropDown(ValueSheetName As String, ValueRangeString As String, CreateOnSheetName As String, CreateInRangeString As String, FieldName As String)
    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName) 'The sheet containing the values
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString) 'The range containing the values
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName) 'The sheet containing the values
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim InputTitle As String:  InputTitle = "Please Select a Value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a Value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True 'Show input message on hover
    Dim ShowError As Boolean:  ShowError = True 'Show error message on error
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop 'Stop on invalid value
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual 'Value must be equal to one of the Values from the ValidationFormula1
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address 'Formula referencing the values from the ValueRange
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)
End Sub


'An example using the ExampleCreateDropDown
Private Sub ExampleCreateDropDown()
    Call CreateDropDown(ValueSheetName:="Test", ValueRangeString:="C1:C5", CreateOnSheetName:="Test", CreateInRangeString:="B1", FieldName:="test2")
End Sub


'The full option function if you need more configurable options
'To create a dropdown in a cell based on a list of values in a range
'Validation: https://msdn.microsoft.com/en-us/library/office/ff840078.aspx
'ValidationTypes: XlDVType  https://msdn.microsoft.com/en-us/library/office/ff840715.aspx
'ValidationAlertStyle:  XlDVAlertStyle  https://msdn.microsoft.com/en-us/library/office/ff841223.aspx
'XlFormatConditionOperator  https://msdn.microsoft.com/en-us/library/office/ff840923.aspx
'See example below ExampleCreateDropDownWithValidationInCell
Public Sub CreateDropDownWithValidationInCell(CreateInRange As Range, _
                                        Optional InputTitle As String = "", _
                                        Optional InputMessage As String = "", _
                                        Optional ErrorTitle As String = "", _
                                        Optional ErrorMessage As String = "", _
                                        Optional ShowInput As Boolean = True, _
                                        Optional ShowError As Boolean = True, _
                                        Optional ValidationType As XlDVType = xlValidateList, _
                                        Optional ValidationAlertStyle As XlDVAlertStyle = xlValidAlertStop, _
                                        Optional ValidationOperator As XlFormatConditionOperator = xlEqual, _
                                        Optional ValidationFormula1 As Variant = "", _
                                        Optional ValidationFormula2 As Variant = "")

    With CreateInRange.Validation
        .Delete
        .Add Type:=ValidationType, AlertStyle:=ValidationAlertStyle, Operator:=ValidationOperator, Formula1:=ValidationFormula1, Formula2:=ValidationFormula2
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = InputTitle
        .ErrorTitle = ErrorTitle
        .InputMessage = InputMessage
        .ErrorMessage = ErrorMessage
        .ShowInput = ShowInput
        .ShowError = ShowError
    End With
End Sub


'An example using the CreateDropDownWithValidationInCell
Private Sub ExampleCreateDropDownWithValidationInCell()
    Dim ValueSheetName As String: ValueSheetName = "Hidden" 'The sheet containing the values
    Dim ValueRangeString As String: ValueRangeString = "C7:C9" 'The range containing the values
    Dim CreateOnSheetName As String: CreateOnSheetName = "Test"  'The sheet containing the dropdown
    Dim CreateInRangeString As String: CreateInRangeString = "A1" 'The range containing the dropdown

    Dim ValueSheet As Worksheet
    Set ValueSheet = Worksheets(ValueSheetName)
    Dim ValueRange As Range: Set ValueRange = ValueSheet.Range(ValueRangeString)
    Dim CreateOnSheet As Worksheet
    Set CreateOnSheet = Worksheets(CreateOnSheetName)
    Dim CreateInRange As Range: Set CreateInRange = CreateOnSheet.Range(CreateInRangeString)
    Dim FieldName As String: FieldName = "Testing Dropdown"
    Dim InputTitle As String:  InputTitle = "Please Select a value"
    Dim InputMessage As String:  InputMessage = "for " & FieldName
    Dim ErrorTitle As String:  ErrorTitle = "Please Select a value"
    Dim ErrorMessage As String:  ErrorMessage = "for " & FieldName
    Dim ShowInput As Boolean:  ShowInput = True
    Dim ShowError As Boolean:  ShowError = True
    Dim ValidationType As XlDVType:  ValidationType = xlValidateList
    Dim ValidationAlertStyle As XlDVAlertStyle:  ValidationAlertStyle = xlValidAlertStop
    Dim ValidationOperator As XlFormatConditionOperator:  ValidationOperator = xlEqual
    Dim ValidationFormula1 As Variant:  ValidationFormula1 = "=" & ValueSheetName & "!" & ValueRange.Address
    Dim ValidationFormula2 As Variant:  ValidationFormula2 = ""

    Call CreateDropDownWithValidationInCell(CreateInRange, InputTitle, InputMessage, ErrorTitle, ErrorMessage, ShowInput, ShowError, ValidationType, ValidationAlertStyle, ValidationOperator, ValidationFormula1, ValidationFormula2)

End Sub

Понравилась статья? Поделить с друзьями:
  • Visual basic microsoft word 2007
  • Visual basic in excel for mac
  • Visual basic for word and excel
  • Visual basic for excel процедуры
  • Visual basic for excel для начинающих