Как создать combobox 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.

Excel for Microsoft 365 Excel 2021 Excel 2019 Excel 2016 Excel 2013 Excel 2010 Excel 2007 Excel Starter 2010 More…Less

When you want to display a list of values that users can choose from, add a list box to your worksheet.

Sample list box

Add a list box to a worksheet

  1. Create a list of items that you want to displayed in your list box like in this picture.

    value list for use in combo box

  2. Click Developer > Insert.

    Note: If the Developer tab isn’t visible, click File > Options > Customize Ribbon. In the Main Tabs list, check the Developer box, and then click OK.

  3. Under Form Controls, click List box (Form Control).

    the list box form control button

  4. Click the cell where you want to create the list box.

  5. Click Properties > Control and set the required properties:

    Proprties for the list box control.

    • In the Input range box, type the range of cells containing the values list.

      Note: If you want more items displayed in the list box, you can change the font size of text in the list.

    • In the Cell link box, type a cell reference.

      Tip: The cell you choose will have a number associated with the item selected in your list box, and you can use that number in a formula to return the actual item from the input range.

    • Under Selection type, pick a Single and click OK.

      Note: If you want to use Multi or Extend, consider using an ActiveX list box control.

Add a combo box to a worksheet

You can make data entry easier by letting users choose a value from a combo box. A combo box combines a text box with a list box to create a drop-down list.

Combo box

You can add a Form Control or an ActiveX Control combo box. If you want to create a combo box that enables the user to edit the text in the text box, consider using the ActiveX Combo Box. The ActiveX Control combo box is more versatile because, you can change font properties to make the text easier to read on a zoomed worksheet and use programming to make it appear in cells that contain a data validation list.

  1. Pick a column that you can hide on the worksheet and create a list by typing one value per cell.

    value list for use in combo box

    Note: You can also create the list on another worksheet in the same workbook.

  2. Click Developer > Insert.

    Note: If the Developer tab isn’t visible, click File > Options > Customize Ribbon. In the Main Tabs list, check the Developer box, and then click OK.

  3. Pick the type of combo box you want to add:

    • Under Form Controls, click Combo box (Form Control).

      Or

    • Under ActiveX Controls, click Combo Box (ActiveX Control).

      Insert combo box

  4. Click the cell where you want to add the combo box and drag to draw it.

Tips: 

  • To resize the box, point to one of the resize handles, and drag the edge of the control until it reaches the height or width you want.

  • To move a combo box to another worksheet location, select the box and drag it to another location.

Format a Form Control combo box

  1. Right-click the combo box and pick Format Control.

  2. Click Control and set the following options:

    Format control dialog box

    • Input range: Type the range of cells containing the list of items.

    • Cell link: The combo box can be linked to a cell where the item number is displayed when you select an item from the list. Type the cell number where you want the item number displayed.

      For example, cell C1 displays 3 when the item Sorbet is selected, because it’s the third item in our list.

      Linked cell shows item number when item is selected.

      Tip: You can use the INDEX function to show an item name instead of a number. In our example, the combo box is linked to cell B1 and the cell range for the list is A1:A2. If the following formula, is typed into cell C1: =INDEX(A1:A5,B1), when we select the item «Sorbet» is displayed in C1.

      Enter formula to show item from linked cell

    • Drop-down lines: The number of lines you want displayed when the down arrow is clicked. For example, if your list has 10 items and you don’t want to scroll you can change the default number to 10. If you type a number that’s less than the number of items in your list, a scroll bar is displayed.

      Scroll bar is displayed.

  3. Click OK.

Format an ActiveX combo box

  1. Click Developer > Design Mode.

  2. Right-click the combo box and pick Properties, click Alphabetic, and change any property setting that you want.

    Here’s how to set properties for the combo box in this picture:

    Example of a combo box.

    Property settings for ActiveX combo box.

    To set this property

    Do this

    Fill color

    Click BackColor > the down arrow > Pallet, and then pick a color.

    Color fill property for a combo box.

    Font type, style or size

    Click Font > the button and pick font type, size, or style.

    Setting for fonts in text box

    Font color

    Click ForeColor > the down arrow > Pallet, and then pick a color.

    Link a cell to display selected list value.

    Click LinkedCell

    Link Combo Box to a list

    Click the box next to ListFillRange and type the cell range for the list.

    Change the number of list items displayed

    Click the ListRows box and type the number of items to be displayed.

  3. Close the Property box and click Designer Mode.

  4. After you complete the formatting, you can right-click the column that has the list and pick Hide.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

See Also

Overview of forms, Form controls, and ActiveX controls on a worksheet

Add a check box or option button (Form controls)

Need more help?

Multiple columns of data within a UserForm ComboBox drop-down menu in Excel.

I’ll show you an easy way to do this and a more complex way to do this using VBA.

Sections:

Multi-Column ComboBox from Worksheet Data (Easy Method)

Multi-Column UserForm ComboBox using VBA

Get Data from any Column of the ComboBox

Notes

Multi-Column ComboBox from Worksheet Data (Easy Method)

This is the easiest method, but it also requires that you keep your list of data within the worksheet in Excel.

  1. Setup your data in columns like this in the worksheet:
    e26146074bfc21e7ca0e65eb0cd27272.png
    You can have as many columns as you need and you could place them on any worksheet, even hidden ones.
  2. Go to the VBA window (Alt + F11) > Double-click the UserForm from the Project Explorer (Ctrl + R) > Click on the ComboBox and look to the Properties Window (F4).
    26e22cd023a9692c4bbfdcbcc46bb304.png
  3. Change the ColumnCount property to the number of columns that you have.
    2e133afc5f29e113db86e93103211009.jpg
  4. Go to the RowSource property and input the range reference of the data for the menu. In this example, it is A9:B11.
    18978caccf73081bf4614e656c53bc0a.jpg
  5. That’s it! 

Run the form and you’ll see the multi-column ComboBox:

2d4a80f929eff6984f8b206efa340d56.png

Adjust the Column Width

You may notice that the widths of the columns in the menu are not good, they are too big, and this is also easy to fix.

Look to the ColumnWidths property and set the width for each column of data.

bdcde03a008df5c207daacf3468ad619.jpg

Separate the widths of each column using a semicolon. If you have 2 columns it could be like 20;50 and for three columns 20;50;30 etc.

Here, I entered 20 for the first column and 50 for the second column — Excel will automatically place the «pt» at the end of it once you enter the numbers and run the form.

Play around with the numbers until it fits your data.

Here is what the menu in our form now looks like after adjusting the column widths:

2cad986ef8543400d9f1b2b2e75224c7.png

Multi-Column UserForm ComboBox using VBA

You can manage and maintain multi-column lists within the code for a UserForm; however, this can be a lot more confusing than the other method, which was illustrated above.

The code for this goes into the UserForm_Initialize() event inside the code section for the form. (In the Project Explorer, right-click the form and click View Code and then select UserForm from the left drop-down and Initialize from the right drop-down menu.)

The name of the ComboBox is ComboBox1.

First, declare a variable that says how many rows the list will be:

Dim RowValue(2, 1) As Variant

2 is the number or total rows minus 1.

1 is the number of total columns minus 1.

Tell the form how many columns there will be in the ComboBox:

ComboBox1.ColumnCount = 2

Tell the form how wide each column will be:

ComboBox1.ColumnWidths = "20;50"

20 is for the first column.

50 is for the second column.

Each column is separated with a semicolon. Play around with the widths until your data fits nicely.

Add the Data:

'Row 1
RowValue(0, 0) = "1"
RuowVale(0, 1) = "Item 1"

'Row 2
RowValue(1, 0) = "2"
RowValue(1, 1) = "Item 2"

'Row 3
RowValue(2, 0) = "3"
RowValue(2, 1) = "Item 3"

Note: the rows and columns start with zero and not 1!

Here is how to reference the rows and columns:

Row 1 Column 1: RowValue(0, 0) 

Row 1 Column 2: RowValue(0, 1) 

Row 2 Column 1: RowValue(1, 0)

Row 2 Column 2: RowValue(1, 1)

Etc.

Follow the pattern to add more rows and more columns.

Put the Values into the ComboBox:

ComboBox1.List = RowValue

All Code Put Together

'Add items to the ComboBox - Multi-Column

'Declare the array variable.
'Say how many rows there will be.
Dim RowValue(2, 1) As Variant

'Say how many columns there will be
ComboBox1.ColumnCount = 2

'Set Column Widths
ComboBox1.ColumnWidths = "20;50"

'Row 1
RowValue(0, 0) = "1"
RowValue(0, 1) = "Item 1"

'Row 2
RowValue(1, 0) = "2"
RowValue(1, 1) = "Item 2"

'Row 3
RowValue(2, 0) = "3"
RowValue(2, 1) = "Item 3"

'Put the values into the ComboBox
ComboBox1.List = RowValue

Result

2e2fd0ed82267577feb0d3deb2ee7582.png

Get Data from Any Column of the ComboBox

When you get values from a multi-column ComboBox, you have to choose which data from which column you will get.

ComboBox1.Column(0)

ComboBox1 is the name of the ComboBox.

Column(0) specifies from which column to get the data. Zero (0) is the first column; 1 is the second column; etc.

In the attached file for this tutorial, two buttons have been added to display these values in a message box pop-up window. Column 1 and Column 2

d9c1e33b4d269e61eda4607e10e9ed1e.png

Note: no error-check has been implemented in this example; this means that you will get an error if you click the Column 1 or Column 2 buttons without first making a selection from the ComboBox.

Notes

Multi-column ComboBox controls can be tricky and annoying to maintain. Only use them if you really must use them.

Download the sample file for this tutorial to see these examples in Excel. (In the sample file, the Column 1 and Column 2 buttons will cause an error if you click them before making a selection from the ComboBox; this isn’t a big deal; I wanted the examples to be as easy-to-understand as possible and so error-checking code was omitted.)

Similar Content on TeachExcel

Complex Structured References (Table Formulas) in Excel

Tutorial:
How to use complex structured references, table formulas, in Excel.

If you don’t already…

Ignore Blanks in a Data Validation List in Excel

Tutorial:
I will show you 3 ways to remove the blanks from a Data Validation dropdown menu in Excel…

Multi-Page UserForm

Tutorial: You can have multiple tabs of data on a single UserForm and this allows you to, effectivel…

Multiple Selections in a ListBox

Tutorial: There are two different kinds of multiple item selections that you can have for a ListBox …

SUMIFS Examples in Excel

Tutorial:
Excel tutorial for the SUMIFS function — this includes 15 different examples that show yo…

8 Tips to Become an Expert in Conditional Formatting for Excel

Tutorial:
Become a master of Conditional Formatting in Excel! This tutorial covers 8 tips and trick…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

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 Excel. ComboBox (заполнение поля со списком)

Автор Время не ждёт Опубликовано 14.03.2018 Добавить комментарий к записи VBA Excel. ComboBox (заполнение поля со списком)

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

  1. Заполнение ComboBox методом AddItem
  2. Заполнение ComboBox значениями из массива
  3. Заполнение ComboBox значениями из ячеек

Заполнение ComboBox методом AddItem

Создайте пользовательскую форму UserForm1 и разместите на ней поле со списком ComboBox1. Используйте метод AddItem для заполнения элемента управления значениями:

1

2

3

4

5

6

7

8

9

10

Sub Test1()

    With UserForm1.ComboBox1

        .AddItem «Кружка»

        .AddItem «Стакан»

        .AddItem «Бокал»

        .AddItem «Пиала»

        .AddItem «Фужер»

    End With

UserForm1.Show

End Sub

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

Заполнение ComboBox значениями из массива

Для заполнения элемента управления ComboBox значениями из массива будем использовать свойство поля со списком List и функцию Array:

Sub Test2()

    With UserForm1

        .ComboBox1.List = Array(«Кружка», «Стакан», «Бокал», «Пиала», «Фужер»)

        .Show

    End With

End Sub

Результат выполнения кода будет таким же, как и на предыдущем изображении.

Таким же образом можно использовать не только функцию Array, но и переменную массива, предварительно объявленную и заполненную значениями:

Sub Test3()

    Dim a(4) As String

        a(0) = «Кружка»

        a(1) = «Стакан»

        a(2) = «Бокал»

        a(3) = «Пиала»

        a(4) = «Фужер»

    With UserForm1

        .ComboBox1.List = a

        .Show

    End With

End Sub

Заполнение ComboBox значениями из ячеек

Для заполнения поля со списком значениями из диапазона ячеек рабочего листа будем использовать свойство комбинированного списка RowSource, предварительно заполнив диапазон «A1:A5» активного листа уже известными значениями:

Sub Test4()

    With UserForm1

        .ComboBox1.RowSource = «A1:A5»

        .Show

    End With

End Sub

Чтобы присвоить элементу управления ComboBox значения из диапазона ячеек любого рабочего листа, добавьте ссылку на него перед наименованием диапазона, например, замените «A1:A5» на «Лист1!A1:A5», и поле со списком будет заполнено значениями ячеек «A1:A5», расположенных на листе с именем «Лист1».

Эти же способы используются и для заполнения значениями элемента управления ListBox.

Иногда возникает необходимость заполнения элементов управления ListBox и ComboBox уникальными значениями из диапазона ячеек с повторяющимся содержимым. Смотрите, как отсортировать уникальные элементы из списка. Опубликовано 14.03.2018 Автор Время не ждёт Рубрики VBA Excel

Понравилась статья? Поделить с друзьями:
  • Как создание оглавления в word 2007
  • Как создание надстройки в excel
  • Как создание кроссворда в excel
  • Как создание дерева excel
  • Как создание буклеты в word