Заполнение combobox vba с листа excel

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

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

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

Sub Test1()

    With UserForm1.ComboBox1

        .AddItem «Кружка»

        .AddItem «Стакан»

        .AddItem «Бокал»

        .AddItem «Пиала»

        .AddItem «Фужер»

    End With

UserForm1.Show

End Sub

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

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

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

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

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

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

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

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

ComboBox1.RemoveItem Index

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

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

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

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

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

Private Sub UserForm_Initialize()

    ComboBox1.List = Лист8.[A1:A15].Value

End Sub

Или по одному:

Private Sub UserForm_Initialize()

    With ComboBox1

        .Clear

        .AddItem «Апельсин»

        .AddItem «Банан»

        .AddItem «Виноград»

        .AddItem «Груша»

        .AddItem «Хурма»

    End With

End Sub

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

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

Private Sub Workbook_Open()

    Лист8.ComboBox1.List = Лист8.[A1:A15].Value

End Sub

Или по одному:

Private Sub Workbook_Open()

    With Лист8.ComboBox1

        .Clear

        .AddItem «Апельсин»

        .AddItem «Банан»

        .AddItem «Виноград»

        .AddItem «Груша»

        .AddItem «Хурма»

    End With

End Sub


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

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

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

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

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

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

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

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

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

Private Sub UserForm_Initialize()

    With ComboBox1

        .AddItem «Камень»

        .AddItem «Ножницы»

        .AddItem «Бумага»

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

        .Value = «Выберите значение»

    End With

End Sub

Добавление значения по умолчанию в текстовое поле ComboBox из имеющегося списка:

Private Sub UserForm_Initialize()

    With ComboBox1

        .AddItem «Камень»

        .AddItem «Ножницы»

        .AddItem «Бумага»

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

        .ListIndex = 0

    End With

End Sub

Нумерация списка ComboBox начинается с нуля, поэтому приведенный выше код отобразит значение по умолчанию — «Камень».


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

  • Remove From My Forums
  • Question

  • Hi there,

    I have sheet , with these values in Range A:

    AA

    BB

    CC

    AA

    BB

    CC

    v

    AA

    gh

    and in the same Worksheet I have a combobox that I want it to show unique value from range A

    How can I do it, please?

    Regards

    • Edited by

      Thursday, September 27, 2012 6:36 PM

Answers

  • '*** Add unique items on a UserForm's ComboBox from a source Range ***
    
    'How to use:
    'Create a ComboBox called ComboBox1 in a UserForm
    'Paste this code in the class of the UserForm
    'In the VBE, click on Tools >> References. Search for the
    'Microsoft ActiveX 2.0 Data Objects Library reference, check it and click OK.
    'In order for this code to work, this workbook has to be saved in any path of your computer.
    'Executing it in a new non-saved workbook won't work.
    'By Felipe Costa Gualberto, 2012, http://www.ambienteoffice.com.br
    
    Option Explicit
    
    Public cn As Connection
    
    Private Sub UserForm_Initialize()
        CreateConnection
        
        'You may put one header line in the source range.
        'Example:
        'A1 = Names, A2 = Felipe, A3 = Rodrigo, A4 = Felipe and so on.
        PopulateControl ComboBox1, Sheets("Sheet1").Columns("A")
    End Sub
    
    Private Sub PopulateControl(ctrl As Control, rngSource As Range)
        'ctrl can be a ComboBox or ListBox control
        'Use, preferably entire Columns as rngSource parameter.
        
        Dim sSql As String
        Dim sWorksheet As String
        Dim sField As String
        Dim rs As ADODB.Recordset
        
        Set rs = New ADODB.Recordset
        
        sWorksheet = "[" & rngSource.Parent.Name & "$]"
        sField = "[" & rngSource.Range("A1") & "]"
        
        sSql = ""
        sSql = sSql & " " & "SELECT DISTINCT " & sField
        sSql = sSql & " " & "FROM " & sWorksheet
        sSql = sSql & " " & "WHERE " & sField & " IS NOT NULL"
                    
        Set rs = cn.Execute(sSql)
        
        ctrl.Clear
        Do While Not rs.EOF
            ctrl.AddItem rs.Fields(0)
            rs.MoveNext
        Loop
        rs.Close
    
    End Sub
    
    Private Sub UserForm_Terminate()
        cn.Close
        Set cn = Nothing
    End Sub
    
    Private Sub CreateConnection()
        Dim sTemp As String
        
        Set cn = New ADODB.Connection
        
        If Val(Application.Version) < 12 Then 'Excel 97-2003
            sTemp = "Provider=Microsoft.Jet.OLEDB.4.0;"
        Else 'Excel 2007-2010
            sTemp = "Provider=Microsoft.ACE.OLEDB.12.0;"
        End If
        
        sTemp = sTemp & "Data Source=" & ThisWorkbook.FullName & ";" & _
          "Extended Properties=Excel 8.0"
        cn.ConnectionString = sTemp
        
        cn.Open
    End Sub


    Felipe Costa Gualberto — http://www.ambienteoffice.com.br

    • Marked as answer by
      Admin-Dev
      Friday, September 28, 2012 2:01 PM

0 / 0 / 0

Регистрация: 29.11.2014

Сообщений: 23

1

15.12.2014, 22:02. Показов 13320. Ответов 13


Студворк — интернет-сервис помощи студентам

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



0



Alex77755

11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

15.12.2014, 23:36

2

процедура:

Visual Basic
1
2
3
4
5
6
7
Private Sub Обновить_список()
ComboBox1.Clear
Const iR = 65536: iC = "A"
iRw = Columns(iC).Rows(iR).End(xlUp).Row
ComboBox1.List = range("A3:A" & iRw).value
ComboBox1.ListIndex = 0
End Sub



0



0 / 0 / 0

Регистрация: 29.11.2014

Сообщений: 23

16.12.2014, 10:07

 [ТС]

3

Я новичок в VBA … у меня 3 листа … как мне привязать его к одному.. мне нужны данные с первого листа с ячейки B2 и вниз

Добавлено через 9 минут
И совсем забыл … имеются данные анализов.. нужно чтобы при выборе пациента в Comboboxе, автоматом выбирались показатели анализов и выводились на форме



0



0 / 0 / 0

Регистрация: 10.06.2011

Сообщений: 8

16.12.2014, 11:34

4

Цитата
Сообщение от Alex77755
Посмотреть сообщение

ComboBox1.ListIndex = 0

А что делает эта строчка?



0



414 / 262 / 82

Регистрация: 27.10.2012

Сообщений: 860

16.12.2014, 18:16

5

Уберите эту строку и увидите разницу.



0



0 / 0 / 0

Регистрация: 10.06.2011

Сообщений: 8

16.12.2014, 18:35

6

Создала пример. Почему-то код вообще Combobox1 не видит…Вопрос по Combobox.rar



0



Alex77755

11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

16.12.2014, 20:15

7

По тому, что код находится в модуле.
В таком случае нужно полние имя контрола

Visual Basic
1
Лист1.ComboBox1.Clear

Вложения

Тип файла: rar Ответ по Combobox.rar (18.7 Кб, 152 просмотров)



1



11482 / 3773 / 677

Регистрация: 13.02.2009

Сообщений: 11,145

16.12.2014, 20:17

8

И совсем забыл
Создала пример

И уж как-то определись! с полом-то



1



0 / 0 / 0

Регистрация: 10.06.2011

Сообщений: 8

16.12.2014, 21:23

9

Спасибо Alex77755!
и поняла что делает ListIndex — выбирает соответствующее значение в комбобоксе.



0



0 / 0 / 0

Регистрация: 15.01.2017

Сообщений: 2

16.01.2017, 15:20

10

подскажите как забить данными несколько comboboxоф на форме с разных листов, точнее с 2х
при том что активный должен быть третий



0



Vlad999

3827 / 2254 / 751

Регистрация: 02.11.2012

Сообщений: 5,930

16.01.2017, 15:25

11

Цитата
Сообщение от Gemlit
Посмотреть сообщение

при том что активный должен быть третий

это вы о чем?
как то так. более точно при наличии файла и нормального описания.

Visual Basic
1
2
ComboBox1.List = sheets("Лист1").range("A3:A20").value
ComboBox2.List = sheets("Лист2").range("B3:B20").value



0



Gemlit

0 / 0 / 0

Регистрация: 15.01.2017

Сообщений: 2

16.01.2017, 15:49

12

Цитата
Сообщение от Vlad999
Посмотреть сообщение

это вы о чем?
как то так. более точно при наличии файла и нормального описания.

при использование вот такого кода

Visual Basic
1
2
3
4
5
ComboBox3.Clear
Const iR = 65536: iA = "A"
iRw = Columns(iA).Rows(iR).End(xlUp).Row
ComboBox3.List = Sheet5.Range("b8:b" & iRw).Value
ComboBox3.ListIndex = 0

combobox заполняется корректно только на sheet5, файл не рискну скидывать там все еще более запутанно



0



3827 / 2254 / 751

Регистрация: 02.11.2012

Сообщений: 5,930

16.01.2017, 16:00

13

у вас combobox листа или формы?

Цитата
Сообщение от Gemlit
Посмотреть сообщение

файл не рискну скидывать там все еще более запутанно

создайте новый с данными необходимыми для решения вашей задачи.



0



0 / 0 / 0

Регистрация: 23.04.2018

Сообщений: 42

18.04.2019, 16:54

14

Здравствуйте! Делаю макрос в ворде, как подтянуть в комбобокс умную таблицу из экселя?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

18.04.2019, 16:54

14

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

VBA – Userform Combobox

In userform, we can have a combobox to display list of items as dropdown. User will be able to choose one of the items from this list.

To use this control, We should know how to add items, remove or find selected or active items.

This page has the code snippets that helps to add combo items in different ways.

1.Combobox ADDITEMS: Add constant values

If there is a list of items in a worksheet or if you would like to add defined number of items to a combobox, use this code.

Sub Combobox_Additems()
    'Add 1st item to index 0 - First item in list
    ComboBox1.AddItem "A", 0
    
    'Add 2nd item to index 1 - 2nd item in list
    ComboBox1.AddItem "B", 1
    
    'Add 3rd item to index 0 - so C becomes first in list
    ComboBox1.AddItem "C", 0
End Sub

Syntax: ComboboxObject.AddItems <value>, [<index>]

In the parameter “value” is mandatory. “index” is optional. You can either mention the index otherwise the system will assign the index on its own in incrementing order.

2.ComboBox Additems from Excel Range

It is easy to use the above methods to add items in combobox if there are defined set of entries.

But if there is a big list of items, then it is better to code a automated way through a loop like the below cde snippet.

Sub Combobox_Additems_from_Range()
    Dim iRow As Double
    
    'Add items in loop
    For iRow = 1 To 10
        ComboBox1.AddItem ThisWorkbook.Sheets(1).Cells(iRow, 1)
    Next
End Sub

It is possible to have identical or duplicate items in a list. So, if the above code is executed twice then same items will be added multiple times.

Make sure to clear Combobox items, before processing the loop or code in a way to avoid adding duplicate entries.

This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically.

Form controls are not as flexible as ActiveX controls but are compatible with earlier versions of Excel. You can find the controls on the developer tab.

Table of Contents

  1. Create a combobox using vba
  2. Assign a macro — Change event
  3. Add values to a combobox
  4. Remove values from a combo box
  5. Set the default value in a combo box
  6. Read selected value
  7. Link selected value
  8. Change combobox properties
  9. Populate combox with values from a dynamic named range
  10. Populate combox with values from a table
  11. Currently selected combobox

Watch this video about Combo Boxes

Create a combobox using vba

create-combobox1

Sub CreateFormControl()

'Worksheets("Sheet1").DropDowns.Add(Left, Top, Width, Height)
Worksheets("Sheet1").DropDowns.Add(0, 0, 100, 15).Name = "Combo Box 1"

End Sub

Recommended article

Recommended articles

test

Back to top

Assign a macro — Change event

You can assign a macro to a combobox by press with right mouse button oning on the combobox and select «Assign Macro». Select a macro in the list and press ok!

This subroutine does the same thing, it assigns a macro named «Macro1» to «Combo box 1» on sheet 1. Macro1 is rund as soon as the selected value in the combo box is changed.

Sub AssignMacro()
Worksheets("Sheet1").Shapes("Combo Box 1").OnAction = "Macro1"
End Sub

Recommended article

Recommended articles

test

Back to top

Add values to a combo box

You can add an array of values to a combo box. The list method sets the text entries in a combo box, as an array of strings.

Sub PopulateCombobox1()
Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.List = _ 
Worksheets("Sheet1").Range("E1:E3").Value
End Sub

The difference with the ListFillRange property is that the combo box is automatically updated as soon as a value changes in the assigned range. You don´t need to use events or named ranges to automatically refresh the combo box, except if the cell range also changes in size.

Sub PopulateCombobox2()
Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.ListFillRange = _
"A1:A3"
End Sub

You can also add values one by one.

Sub PopulateCombobox3()
With Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat
.AddItem "Sun"
.AddItem "Moon"
.AddItem "Stars"
End Sub

Back to top

Recommended article

Recommended articles

test

Remove values from a combo box

RemoveAllItems is self-explanatory.

Sub RemoveAllItems()

Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.RemoveAllItems

End Sub

The RemoveItem method removes a value using a index number.

Sub RemoveItem()

Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.RemoveItem 1

End Sub

The first value in the array is removed.

Recommended article

Recommended articles

test

How to use DIALOG BOXES
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]

Back to top

Set the default value in a combo box

The ListIndex property sets the currently selected item using an index number. ListIndex = 1 sets the first value in the array.

Sub ChangeSelectedValue()
With Worksheets("Sheet1").Shapes("Combo Box 1")
.List = Array("Apples", "Androids", "Windows")
.ListIndex = 1
End With
End Sub

Recommended article

Recommended articles

test

Back to top

Read selected value

The ListIndex property can also return the index number of the currently selected item. The list method can also return a value from an array of values, in a combo box. List and Listindex combined returns the selected value.

Sub SelectedValue()
With Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat
MsgBox "ListIndex: " & .ListIndex & vbnewline & "List value:" .List(.ListIndex)
End With
End Sub

Recommended article

Recommended articles

Back to top

Link selected value

Cell F1 returns the index number of the selected value in combo box 1.

Sub LinkCell()

Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.LinkedCell = "F1"

End Sub

Cell G1 returns the selected value in combo box 1.

Sub LinkCell2()

With Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat
    Worksheets("Sheet1").Range("G1").Value = .List(.ListIndex)
End With

End Sub

Recommended article

Recommended articles

Back to top

Change combobox properties

Change the number of combo box drop down lines.

Sub ChangeProperties()
Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.DropDownLines = 2
End Sub

Back to top

Populate combox with values from a dynamic named range

I created a dynamic named range Rng, the above picture shows how.

Sub PopulateFromDynamicNamedRange()

Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.ListFillRange = "Rng"

End Sub

You can do the same thing as the subroutine accomplishes by press with right mouse button oning the combo box and then press with left mouse button on «Format Control…». Input Range: Rng
Back to top

Populate combox with values from a table

Sub PopulateFromTable()

Worksheets("Sheet1").Shapes("Combo Box 1").ControlFormat.List = _
[Table1[DESC]]

End Sub

Back to top

Currently selected combobox

It is quite useful to know which combo box the user is currently working with. The subroutine below is assigned to Combo Box 1 and is rund when a value is selected. Application.Caller returns the name of the current combo box.

Sub CurrentCombo()

MsgBox Application.Caller

End Sub

Back to top

test

Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]

test

Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]

test

test

Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]

test

test

Excel calendar [VBA]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]

test

test

Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]

test

Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]

test

test

test

Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]

test

test

test

test

test

test

test

test

Search all workbooks in a folder
Today I’ll show you how to search all Excel workbooks with file extensions xls, xlsx and xlsm in a given folder for a […]

test

Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]

test

test

test

Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]

test

Copy selected rows (checkboxes) (2/2)
This article demonstrates a macro that copies selected rows based on enabled check boxes. The image above shows data on […]

test

test

test

Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]

test

test

Analyze word frequency in a cell range
This article demonstrates two ways to calculate the number of times each word appears in a given range of cells. […]

test

Excel calendar [VBA]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]

test

test

Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]

test

test

Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]

test

Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]

test

test

Latest updated articles.

More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.

More than 1300 formulas organized in subcategories.

Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.

Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.

Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.

Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.

Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.

The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.

An Excel feature that lets you visualize data in a graph.

Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.

Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.

VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.

A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.

UDF stands for User Defined Functions and is custom built functions anyone can create.

A list of all published articles.

 

comment.imho

Пользователь

Сообщений: 88
Регистрация: 12.01.2020

#1

05.02.2022 18:42:58

Здравствуйте. Есть такой код.

Код
Private Sub UserForm_Initialize()

ComboBox1.RowSource = "Справочник! A2:A1000"

With UserForm1.ComboBox2
  .AddItem "1"
  .AddItem "2"
  .AddItem "3"
  .AddItem "4"
End With

End Sub

Как для ComboBox1 задать диапазон с А2 до последней занятой строки?

Спасибо.

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#2

05.02.2022 18:50:36

Код
With Woksheets("Справочник")
     LastRow = .UsedRange.Rows.Count + .UsedRange.Row - 1
     ComboBox1.List = .Range("A2:A" & LastRow).Value
End With

Если в столбце А значений меньше, чем в UsedRange (ниже есть строки со значениями в других столбцах):

Код
      LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

Но в этом случае не должно быть скрытых значений внизу диапазона.

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

#3

05.02.2022 18:52:58

Код
Dim LastRow As Long, Arr()
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    Arr = Range(Cells(2, 1), Cells(LastRow, 1)).Value
    Me.combobox1.List = Arr
 

vikttur,
Получаем такую ошибку

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

А что такое Woksxheets? Куда подевалась буква r? Это для начала.

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Это моя коленка съела )

Woksheets

Worksheets
И переменную LastRow объявить нужно. И .Ranges — нет такого…

 

comment.imho

Пользователь

Сообщений: 88
Регистрация: 12.01.2020

#7

05.02.2022 19:56:43

Работает

Код
Private Sub UserForm_Initialize()
With Worksheets("Справочник")
     LastRow = .UsedRange.Rows.Count + .UsedRange.Row
     ComboBox4.List = .Range("A2:A" & LastRow).Value
End With
With Worksheets("Справочник")
    LastRow = .UsedRange.Rows.Count + .UsedRange.Row
    ComboBox5.List = .Range("B2:B" & LastRow).Value
End With
With UserForm1.ComboBox1
  .AddItem "1"
  .AddItem "2"
  .AddItem "3"
  .AddItem "4"
End With
End Sub

Изменено: comment.imho05.02.2022 19:58:36

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

#9

05.02.2022 20:00:05

Цитата
vikttur написал:
моя коленка съела )

за коленку ответишь! )

 

comment.imho

Пользователь

Сообщений: 88
Регистрация: 12.01.2020

#10

05.02.2022 20:04:19

Юрий М, Спасибо. Вроде начинаю понимать.

Код
Private Sub UserForm_Initialize()
Dim LatRow As Long, Arr()
With Worksheets("Справочник")
     LatRow = .Cells(Rows.Count, 1).End(xlUp).Row
     Arr = Range(.Cells(2, 1), .Cells(LatRow, 1)).Value
     ComboBox4.List = Arr
End With
With Worksheets("Справочник")
    LatRow = .Cells(Rows.Count, 2).End(xlUp).Row
    Arr = Range(.Cells(2, 2), .Cells(LatRow, 2)).Value
    ComboBox5.List = .Range("B2:B" & LatRow).Value
End With
With UserForm1.ComboBox1
  .AddItem "1"
  .AddItem "2"
  .AddItem "3"
  .AddItem "4"
End With
End Sub

Изменено: comment.imho05.02.2022 20:07:45

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

Для ComboBox5 определили массив (arr), но не используете его. Почему?

 

comment.imho

Пользователь

Сообщений: 88
Регистрация: 12.01.2020

#12

05.02.2022 20:39:15

Код
Private Sub UserForm_Initialize()
Dim LatRow As Long, Arr()
With Worksheets("Справочник")
     LatRow = .Cells(Rows.Count, 1).End(xlUp).Row
     Arr = Range(.Cells(2, 1), .Cells(LatRow, 1)).Value
     ComboBox4.List = Arr
End With
With Worksheets("Справочник")
    LatRow = .Cells(Rows.Count, 2).End(xlUp).Row
    Arr = Range(.Cells(2, 2), .Cells(LatRow, 2)).Value
    ComboBox5.List = Arr
End With
With UserForm1.ComboBox1
  .AddItem "1"
  .AddItem "2"
  .AddItem "3"
  .AddItem "4"
End With
End Sub
 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#13

05.02.2022 21:05:46

В данном случае использование массива Arr лишнее. А вот Array — в самый раз )

Код
Private Sub UserForm_Initialize()
    Dim LastRow As Long
    
    With Worksheets("Справочник")
        LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        ComboBox4.List = .Range(.Cells(2, 1), .Cells(LastRow, 1)).Value

        LastRow = .Cells(Rows.Count, 2).End(xlUp).Row
        ComboBox5.List = .Range(.Cells(2, 2), .Cells(LatsRow, 2)).Value
    End With
    
    ComboBox1.List = Array(1, 2, 3, 4)
End Sub

Изменено: vikttur05.02.2022 21:07:19

 

Юрий М

Модератор

Сообщений: 60580
Регистрация: 14.09.2012

Контакты см. в профиле

Так можно и последнюю строку не определять в переменную ))

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Это перебор )
Если массив где-то еще использовать — то да, нужен. Например, один раз заполнили «глобальный» массив, потом из него подставляем данные в ListBox при фильтрации по разным параметрам или при поиске по первым буквам. А здесь заполнить массив только для того, чтобы разово передать значения диапазона в список — какой смысл?

 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#16

05.02.2022 22:16:29

я бы это написал так:

Код
Private Sub UserForm_Initialize()
  With Worksheets("Справочник")
    ComboBox4.List = .Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp))
    ComboBox5.List = .Range(.Cells(2, 2), .Cells(Rows.Count, 2).End(xlUp))
  End With
  ComboBox1.List = Array(1, 2, 3, 4)
End Sub

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

Понравилась статья? Поделить с друзьями:
  • Заполнение конверта word скачать
  • Запишите формулы по всем требованиям ms excel составьте для этих формул таблицу по образцу
  • Заполнение квитанций на excel
  • Запишите формулы по всем требованиям ms excel ответы
  • Заполнение документа на vba word