Combobox vba excel как заполнить

от admin

VBA ComboBox

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:

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:

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:

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:

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:

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

vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Combobox vba excel как заполнить

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 для заполнения элемента управления значениями:

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

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

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

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

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

Dim a(4) As String

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

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

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

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

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

How to Populate ComboBox on VBA Userforms

The ComboBox is a Control for VBA userforms that allows the user to choose from a list of options. It is also known as a drop-down menu, but to serve its purpose as a dropdown menu, you’ll first need to populate the combobox for the user so they can actually make a choice. There are two ways to populate a ComboBox with VBA:

  1. With the .AddItem method
  2. With the .List property

The rest of this tutorial will teach you how to add entries to, or populate, your own VBA userform comboboxes, and we’ll have a little fun teaching it!

Create the UserForm

Before we write any code to populate our combobox, we need to create the box itself and the userform on which it lives.

I’m sure you already have your own design, but in this tutorial, our userform will carry the name Combobox_Userform , our command button will be CmdButton_For_CB , and the combobox itself will be ComboBox_Demo1 .

Here is what the layout looks like:

Layout of Userform
Userform with three elements: a combobox, a label, and a button

As you can see, we put default text “Click Here” into the combobox. This is not one of the dropdown options; it’s simply a filler before the user clicks the menu. You can edit it directly by clicking into the combobox in the preview window, just like for the Label and CommandButton controls, but what you really want to do is populate your combobox using VBA code, like we’ll demonstrate in the next section.

Populate the VBA Combobox

In this section, we will show you how to populate a combobox in the UserForm_Initialize VBA Event by either adding items sequentially or reading the values directly from an array.

Accessing the Initialization Event

VBA hands control off to the UserForm_Initialize Event only after the userform has been called. If you want a more in-depth discussion about the logic of showing a userform, check out our Userform Show article. In short, here’s the code for showing our particular userform:

Make sure you place this in a regular Module, not the userform’s dedicated private code.

Populate ComboBox with .List

Now we’re going to begin actually populating the values in our ComboBox. One way to add multiple values to your ComboBox is to use the ComboBox List property, or .List .

To use the ComboBox .List property, you simply need to put your dropdown menu options into an array and separate each dropdown item by a comma. You can use the Array function to create the array needed for the .List property. Don’t forget each option needs quotes since your entries are strings!

Here’s a sample code that goes into the userform’s private code, not a regular module, and adds two items to your dropdown list once the userform is initialized:

Make powerful macros with our free VBA Developer Kit

Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.

Читать:
Sata mode selection что это

When you run this code, you’ll get this beauty:

Userform with ComboBox Opened
The userform with populated combobox open

Notice the userform’s caption is “UserForm3”, but the userform name is ComboBox_Userform . I’m pointing this out because the same distinction applies to your combobox. Don’t get the (Name) and Caption or Text values mixed up! You will get a runtime error if you try to use the caption as the object name. You can change the object name and caption in the Properties window (F4), typically on the bottom left of the VBE.

VBE Properties Window with Name and Caption Highlighted
The Properties Window for Combobox_Userform with the Caption and Name Circled

Populate ComboBox with a Range

You can also use the .List property to populate a userform combobox with a range of cells in your spreadsheet. Take this macro, for example:

This macro will quickly add all the values in range A1:A10 to your ComboBox. It’s incredibly fast and very helpful if your userform is designed to accept data from your spreadsheet.

Populating Multi-Column ComboBox

Speaking of columns of data, the .List property also has an optional second argument, pvargColumn, to let you populate specific columns of a multicolumn ComboBox.

If you want to use the optional arguments in the .List property to create multi-columned comboboxes, there are some extra steps to take.

First you need to change the number of columns in your combobox, much like you would in my tutorial on aligning columns differently in a UserForm ListBox. You can do this under the Properties window mentioned earlier, or you can do it at runtime by using the .ColumnCount property of the combobox object, like this:

Then, you can create a dummy array that matches the dimensions you want for the list of options. Remember the .List array is zero-based. Let’s say you want a 3-row, 2-column list with any kind of data, like numbers or dates, so you dimensionalize an array, like this:

From here, you have two choices. You can either (1) populate your array and then populate your ComboBox with your full array, or (2) populate your ComboBox with an empty array and then fill each array element individually.

Either way, we’ll use the .List property, just like before, to add items to your ComboBox. The second option accesses each “cell” in the list to fill out the final dropdown menu.

Option 1: Pass Full Array to ComboBox
Option 2: Pass Empty Array to ComboBox

Whichever option you choose, you’ll be left with a nice two-column, three-row VBA ComboBox that’s fully populated, like this one:

Dropdown with multiple columns
A Populated Multi-Column ComboBox

Populate ComboBox with .AddItem

If instead you want to add items with methods (as opposed to properties), you can use the ComboBox .AddItem method during initialization. Each time you call the AddItems method, a new item will appear in your ComboBox.

More interestingly, you can use .AddItems to add items dynamically after the userform has already been created.

In code, populating your UserForm ComboBox dynamically would look something like this:

We used the Event UserForm_Click , so when the user clicks on the userform area, an item is added to the bottom of our dropdown list. The initial userform has the default values we added with the .List property, but now we let the user add items by clicking on the userform, as well.

Userform with opened dropdown and several added items
The dropdown menu after clicking on the userform several times

I know this is a silly example, but it demonstrates how you can dynamically alter your combobox when certain conditions are met; in this case, when the user clicks the form.

You could also populate the list with .AddItem in the initialization stage if you wanted, like this:

The VBA ComboBox AddItem method is the most popular way to add items to a userform, although I’ve found both options to be equally flexible.

Imagine you had a lot of rows in a text file or something that you wanted to add to your combobox. You could nest the .AddItem method inside a For Loop to programatically add each item. Placing the AddItem ComboBox method inside a loop is a common practice for populating a UserForm ComboBoxes.

Add Item to Different Positions in ComboBox

The AddItem method of userform comboboxes also accepts an optional second argument: pvargIndex. When included, the pvargIndex tells your combobox where you want to add your new entry.

The items in your combobox range from 0 (at the top) to .ListCount (at the bottom). For example, if you fed the argument a 0, it would add a new entry to the top of your userform. Omitting the argument is the same as passing the AddItem method an argument of ComboBox_Demo1 .ListCount .

Let’s look at a couple examples. In the following code, the “You Clicked Me!” item is added in the first position instead of the default last position.

to place the code at the top of your ComboBox (Position 0).

Let’s take a look at one more example.

In this example, we dynamically populated our combobox by adding an item to the top, bottom and at the 3rd entry in the dropdown menu by specifying a pvargIndex position. Notice how a pvargIndex of 2 added an item to the 3rd slot. Remember, ComboBox indexing begins at position 0!.

ComboBox pvargIndex to add item to dropdown
pvargIndex to add items to ComboBox

Conclusion

Creative developers can use both .List and .AddItem to make interactive userform dropdown lists. By using ComboBoxes (or dropdowns), developers are able to guide user interactions with the program while still allowing a degree of freedom to the end users.

We hope you enjoyed this tutorial. To take your VBA skills to the next level, check out more of our free VBA tutorials. Test your skills by trying to link concepts. For example, can you combine [VBA GetOpenFilename] feature with a ComboBox for an interactive dropdown. When you’re ready to take your VBA to the next level, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

This article was written by Cory Sarver, a contributing writer for The VBA Tutorials Blog. Visit him on LinkedIn and his personal page.

VBA Excel. ComboBox — заполнение поля со списком

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

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

ComboBox, заполненный значениями методом .AddItem

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

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

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

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

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

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

ComboBox, заполненный значениями из диапазона ячеек

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

Очистка ComboBox от значений

Очистить ComboBox можно как от всех значений сразу, так и удалить один или несколько значений (по одному) из списка.

Очистка ComboBox от всего списка значений:

Очистка ComboBox от одного значения:

где Index — порядковый номер элемента в списке ComboBox, нумерация начинается с нуля.

Автоматическое заполнение ComboBox

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

Заполнение ComboBox на форме

Автоматическое заполнение элемента управления ComboBox на пользовательской форме осуществляется с помощью процедуры UserForm_Initialize, размещенной в модуле этой формы:

Заполнение ComboBox на листе

Автоматическое заполнение элемента управления ComboBox из коллекции «Элементы ActiveX» на рабочем листе осуществляется с помощью процедуры Workbook_Open, размещенной в модуле «ЭтаКнига»:

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

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

Вы можете скачать файл Excel с представленными выше примерами. Файл упакован в ZIP-архив. Для проверки работоспособности кода, непосредственно в редакторе VBA помещайте курсор внутри тела каждой процедуры и нажимайте кнопку «Run Sub».

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

Добавление значения по умолчанию вручную

Значение по умолчанию для текстового поля ComboBox можно задать вручную в окне свойств (Properties) выбранного элемента управления:

Выберите ComboBox на форме в редакторе VBA и в окне Properties в поле Value впишите нужное значение.

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

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

Похожие статьи