Excel vba items in combobox

Элемент управления пользовательской формы 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.

Skip to content

VBA ComboBox Excel Macros Examples Codes Adding Clearing Items

Home » Excel VBA » VBA ComboBox Excel Macros Examples Codes Adding Clearing Items

VBA ComboBox Excel Macros Examples Codes for Adding new Items,Adding new Items to another ComboBox based on selection of first ComboBox ,Clearing Tutorials. ComboBox in Excel VBA is one of most useful control in the Excel. You can show the list of items in the ComboBox and user can select any one item and do different operations. In this tutorial, we will explain different example on using ComboBox.

ComboBox in Excel VBA – Example Cases:

  • Add Items to ComboBox while opening Workbook
  • Add Items to ComboBox2 based on ComboBox1 selection
  • Get data to TextBox based on ComboBox2 selection
  • Clear ComboBox Items
  • DownLoad:Example File

Sample ComboBox Design:

  1. GoTo Developer Tab from Menu
  2. GoTo Insert from Controls Part
  3. Insert two ComboBox’s and two TextBox’es from ActiveX Controls
  4. The final design should be as shown below
Screen Shot:

ComboBox in Excel VBA-Design1

Add Items to ComboBox while opening Workbook

You can Add items to the ComboBox while opening the Excel Workbook. The following example will show you how to populate the items in ComboBox while opening excel file.

Code:
Private Sub Workbook_Open()
    
    Application.EnableEvents = False
    'Clear ComboBox1 Items
    Call Clear_ComboBox
    
     'Add Items to ComboBox1 in Sheet1 while opening workbook
    With Sheet1.ComboBox1
        .AddItem "Fruits"
        .AddItem "Vegetables"
        .AddItem "Soaps"
        .AddItem "Beverages"
    End With
     Application.EnableEvents = True
End Sub

Output:

Here is the screen-shot of the ComboBox1 with items.
ComboBox in Excel VBA-Add Items

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. From Project Explorer Double Click on ThisWorkbook
  4. Copy the above code and Paste in the code window
  5. Save the file as macro enabled workbook and Close it
  6. Open the file to see the output
  7. You should see the Items in ComboBox1 as shown above
Add Items to ComboBox2 based on ComboBox1 selection

You can add items to ComboBox2 based on ComboBox1 selection. It is helpful while developing tools. You can provide the user to select item from first ComboBox and add items to second comboBox based on first ComboBox Selection.Please find the following example below.

Code:
'Get Items to ComboBox2 based on ComboBox1 selection
Private Sub ComboBox1_Change()

    'Variable Declaration
    Dim iCnt As Integer
    
    'Clear Combobox2 before loading items
    ComboBox2.Clear
 
    With ComboBox2
        Select Case ComboBox1
            Case "Fruits"
                .AddItem "Apple"
                .AddItem "Pomegranate"
                .AddItem "Grape"
                .AddItem "Pineapple"
                .AddItem "Gouva"
            Case "Vegetables"
                .AddItem "Tomato"
                .AddItem "Brinjal"
                .AddItem "Radish"
                .AddItem "Potato"
                .AddItem "Onion"
            Case "Beverages"
                .AddItem "Pepsi"
                .AddItem "Limca"
                .AddItem "Miranda"
                .AddItem "Sprite"
                .AddItem "Coco Cola"
            Case "Soaps"
                .AddItem "Lux"
                .AddItem "Rexona"
                .AddItem "Dove"
                .AddItem "Lifeboy"
                .AddItem "Liril"
        End Select
    End With

End Sub

Output:

Here is the screen-shot to show you adding the items to second ComboBox based on first ComboBox Selection.
ComboBox in Excel VBA-Add Items to ComboBox2

Instructions:
  1. Please follow the above mentioned design steps
  2. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  3. Double Click on ComboBox1
  4. Copy the above code and Paste in the code window
  5. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  6. Now select Item from Combox1. Now you can see the items in Combox2 based on ComboBox1 selection
Get data to TextBox based on ComboBox2 selection

The following example will show you how to get data to TextBox based on ComoBox2 selection.

Code:
'Get Price based on ComboBox2 selection
Private Sub ComboBox2_Change()
    
    'Variable Declaration
    Dim iRow As Integer
    iRow = 1
    
    'Clear Combobox2 before loading items
    TextBox1.Text = ""
    
    'Get Price based on ComboBox2 selection
    Do
        iRow = iRow + 1
        
    Loop Until ComboBox2.Text = Sheets("Data").Cells(iRow, 3)
    TextBox1.Text = Sheets("Data").Cells(iRow, 4)
    TextBox2.Text = Sheets("Data").Cells(iRow, 5)

End Sub
Output:

Here is the sample screen-shot.
ComboBox in Excel VBA-Output

Instructions:
  1. Please follow the above mentioned design steps
  2. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  3. Double Click on ComboBox2
  4. Copy the above code and Paste in the code window
  5. Goto Developer Tab from the menu, Click on Design Mode in the Sheet1
  6. Now select Item from Combox1 & Combox2. Now you can see the Price and availability of item to the Textbox as aoutput based on ComboBox2 selection
Clear ComboBox Items

You can clear the ComboBox using Clear method. The following procedure will show how to clear the ComboBox items, this procedure will clear the ComboBox items before loading an items to ComboBox.

Code:
Sub Clear_ComboBox()
    
    'Clear ComboBox & TextBox data
    With Sheet1
        .ComboBox1.Clear
        .ComboBox2.Clear
        .TextBox1.Text = ""
        .TextBox2.Text = ""
    End With

End Sub
Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. We can call this procedure to clear ComboBox items before loading items to ComboBox
  6. It will clear items from ComboBox
Example File

Download the example file and Explore it.
ANALYSISTABS – Combo Box

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

36 Comments

  1. Jared
    February 20, 2014 at 6:24 AM — Reply

    I’d like to do the same thing as above with the first two comboboxes, but instead of using item hard-coded into the programming, use group of cells, so, where you see

    Select Case ComboBox1
    Case “Fruits”
    .AddItem “Apple”
    .AddItem “Pomegranate”
    .AddItem “Grape”
    .AddItem “Pineapple”
    .AddItem “Gouva”

    i’d like it to refer to cells that have those values in them, and tell it to keep looking untill it finds a blank cell (meaning theres no more values) so i can feel free to add and delete values as i want, right in the sheet. i’m sure this is possible, and i’ve seen it done, but can someone show me using the above example?

    thanks!

  2. PNRao
    February 20, 2014 at 11:18 PM — Reply

    Hi Jared,

    Here is the solution.
    Assuming that you have the following data in Column A and B:

    Fruits Apple
    Fruits Pomegranate
    Fruits Grape
    Fruits Pineapple
    Fruits Gouva
    Vegetables Tomato
    Vegetables Brinjal
    Vegetables Radish
    Vegetables Potato
    Vegetables Onion
    Beverages Pepsi
    Beverages Limca
    Beverages Miranda
    Beverages Sprite
    Beverages Coco Cola
    Soaps Lux
    Soaps Rexona
    Soaps Dove
    Soaps Lifeboy
    Soaps Liril
    Here is the code:


    Private Sub ComboBox1_Change()
    Dim iCntr As Integer

    iCntr = 1
    'Looping until column A is blank
    ComboBox2.Clear
    Do While Sheets("Sheet1").Cells(iCntr, 1) <> "
    'Checking if the column a is equals to ComboBox1 selected value
    If Sheets("Sheet1").Cells(iCntr, 1) = ComboBox1.Value Then
    'Adding items to ComboBox2, respective items in the Column B
    ComboBox2.AddItem Sheets("Sheet1").Cells(iCntr, 2)
    End If
    iCntr = iCntr + 1
    Loop

    End Sub

    Hope this helps.

    Thanks-PNRao!

  3. Amith
    April 25, 2014 at 1:12 PM — Reply

    Hi,
    I want to add quantity column and want a Total Quantity field in Combo Box with capability to auto sum quantity of Apple.(Suppose we have entered Apple in Row 2 as 100 Qty and Row 5 as 50 Qty in Data sheet.) And when anybody selects Fruit>Apple it will display Quantity as 150. This new part i want to add keeping rest of thing same. Need your help….

  4. PNRao
    April 26, 2014 at 10:52 AM — Reply

    Hi Amith,
    You can loop through the rows and check for the ‘apple’ and the add the respective qty. For example:
    in FruitComboBox_change()
    [vb]
    ‘Assuming Fruit Name in Column A and Qty in Column B
    If Trim(FruitComboBox.Value) <> «» Then
    lRow = 200 ‘Your last row in data sheet
    totQty = 0

    For iCntr = 1 To lRow
    If Sheets(«Data»).Cells(iCntr, 1) = FruitComboBox.Value Then totQty = totQty + Sheets(«Data»).Cells(iCntr, 2)
    Next
    ‘Display the final Qty
    QtyTextBox = totQty
    End If
    [/vb]

    Hope this helps!
    Thanks-PNRao!

  5. Bhawesh
    December 17, 2014 at 5:33 PM — Reply

    Dear sir,
    I would like to know that how i linked different cells rows with the same combobox which populated in different textboxes. kindly help.. Regards, Bhawesh

  6. sharmila
    January 5, 2015 at 10:05 PM — Reply

    good tutorial and well defined example

  7. PNRao
    January 6, 2015 at 8:09 PM — Reply

    Thank you Sharmila! We are glad we could help and hearing good feedback from our readers.
    -PNRao!

  8. Farbood
    February 13, 2015 at 11:10 PM — Reply
  9. Jayanth
    February 16, 2015 at 12:41 PM — Reply

    Hi!
    this is a good and easy to understand example.

    the query i have in my mind is that..

    i have a vb program and an excel sheet separately and i have linked it thru OLEDB connection.

    i have two combo boxes and i have to read data from excel sheet .

    how do i do that ?

  10. klorvalex
    February 25, 2015 at 10:07 PM — Reply

    Good. This helps me a lot. Thanks.

  11. PNRao
    March 2, 2015 at 7:17 PM — Reply

    Thank you klorvalex! You are most welcome to our blog. – PNRao!

  12. PNRao
    March 2, 2015 at 7:26 PM — Reply

    You can get the data from Excel to an arry and assign to ComboBox:
    Example:

    ComboBox1.List=ArrData

    Thanks-PNRao!

  13. PNRao
    March 2, 2015 at 7:29 PM — Reply

    You are most welcome Farbood! We are very glad and happy to hear such a nice feedback.
    Thanks-PNRao!

  14. xuan truong NGUYEN
    August 1, 2015 at 6:11 AM — Reply

    Your explanations and templates are excellent .Thanks a lot

  15. PNRao
    August 2, 2015 at 3:39 AM — Reply

    Thanks for the feedback!
    Regards-PNRao!

  16. japheth
    February 24, 2016 at 7:37 PM — Reply

    Hi guys, am stuck somewhere, av been able to create 2 combo boxes in my form and populated the first one. my question is how can i link the two combo boxes so that the list is combo box 2 depends with the user’s selection in combo box one, which fetches data from an excel worksheet.
    Any help?..Thanx in ADVANCE …

    THIS IS MY CODE (for populating combo box 1)

  17. PNRao
    February 25, 2016 at 10:35 PM — Reply

    Assuming your you have two combo boxes on user form named ComboBox1 and ComboBox2:

    'Initiating ComboBox1 
    Private Sub UserForm_Initialize()
    ComboBox1.AddItem "Set 1"
    ComboBox1.AddItem "Set 2"
    ComboBox1.AddItem "Set 3"
    End Sub
    
    'Populating ComboBox2 while changing the value of ComboBox1
    Private Sub ComboBox1_Change()
    ComboBox2.Clear
    If ComboBox1.Value = "Set 1" Then
        ComboBox2.List = Sheets("YourSheetName").Range("A1:A5").Value
    ElseIf ComboBox1.Value = "Set 2" Then
        ComboBox2.List = Sheets("YourSheetName").Range("B1:B5").Value
    ElseIf ComboBox1.Value = "Set 3" Then
        ComboBox2.List = Sheets("YourSheetName").Range("C1:C5").Value
    End If
    End Sub
    
    

    Hope this helps, Thanks-PNRao!

  18. Roy
    March 1, 2016 at 4:06 PM — Reply

    Hi PNRao,

    Hope you are doing good.
    a very small query. i have a code in which i am taking the input through input box and those values are getting stored in defined cells.what i want to do is the values that i am taking as an input if any of the values is less then a particular value say suppose 50 then that particular cell will return the value with a color red.
    i was doing the following but its not executing anything.

    Dim i As Integer
    i = 1
    Do While Cells(i, 2).Value ”
    If Cells(i, 2).Value < 50 Then
    Cells(i, 2).Font.Color = vbRed
    i = i + 1
    End If
    Loop

    help would be much appreciated.

  19. Marcel Defensor
    March 4, 2016 at 9:30 AM — Reply

    I just can’t create a combobox code that extracts its items direct from a worksheet dependind on the value related to a particular cell. Something like ‘if “a1=2” then “items are this column” else “items are that column”‘.
    Any help will be useful. Thanks.

  20. PNRao
    March 5, 2016 at 6:03 PM — Reply

    Hi Roy,
    increment statement should be out side the if block:

    Sub sbChangeFontColorBasedOnCellValue()
    Dim i As Integer
    i = 1
    Do While Cells(i, 2) <> "
        If Cells(i, 2) < 50 Then
            Cells(i, 2).Font.Color = vbRed
        End If
        i = i + 1
    Loop
    End Sub
    

    Thanks-PNRao!

  21. PNRao
    March 5, 2016 at 6:08 PM — Reply
  22. Jahanzeb
    May 5, 2016 at 4:13 PM — Reply

    Thanks a Lot, It will pay you for your kind support

  23. Bhupender
    May 16, 2016 at 1:46 AM — Reply

    Hi,

    Sir I am a new learner of vba. so could you please uploade the data file of above example. so that i can understand.

    Regards
    Bhupender Singh
    Big fan of yours tutorial

  24. Edgardo
    August 23, 2016 at 11:25 AM — Reply

    i want to select item’s quantity from combo-box and calculate price and it will input in textbox using Visual Basic Studio

  25. Edgardo
    August 23, 2016 at 11:26 AM — Reply

    Hi guys can you please help me? I want select item’s quantity from combo-box and calculate price.

  26. ravikumar
    August 31, 2016 at 3:48 PM — Reply

    hi,

    iam a new to vba code..i have an excel sheet in that I create dropdown list..like

    IF process is main then the list items are
    timeline
    kaizen
    datatabel
    fifolane

    when ever I will select the drop down list value according to that in next cell data will come autopopulate… can you send the code in vba

  27. ravikumar
    August 31, 2016 at 6:17 PM — Reply

    ‘Get Price based on ComboBox2 selection
    Do
    iRow = iRow + 1

    Loop Until ComboBox2.Text = Sheets(“Data”).Cells(iRow, 3)
    TextBox1.Text = Sheets(“Data”).Cells(iRow, 4)
    TextBox2.Text = Sheets(“Data”).Cells(iRow, 5)

    End Sub
    can you explain this code….
    here data in the sense wat…can you pls explain this…this will helpful for me…

  28. pradeep
    September 20, 2016 at 10:53 AM — Reply

    im unable to download the file

  29. PNRao
    October 23, 2016 at 9:46 AM — Reply

    Updated the link, please download the file.
    Thanks-PNRao!

  30. vasim
    January 10, 2017 at 2:22 PM — Reply

    please upload example excel file.

  31. Himanshu
    January 11, 2017 at 4:33 PM — Reply

    Dear Sir,

    Excellent tutorial. I need help with intermediate and advanced excel tutorials. Will you be able to provide tutorials in a structured course format. Thanks

  32. Rajesh
    May 29, 2017 at 1:55 AM — Reply

    Hi. I am stuck at a place where I am selecting the value from the first Combo box and according the value is listed in the second Combo box. Now the challenge for me here is the values of the second combo box is too long , during display the value is left aligned which is easier for the user to select the item but the once the value is selected the value is displayed right aligned which is difficult to identify what was selected. How can I show the value initially and on selecting also the value is left aligned.

    Kindly help.

  33. Catherine Thomas
    June 21, 2017 at 9:21 AM — Reply

    I downloaded this code and modified it for my 2 boxes and it works perfectly – thank you!!!

    Now, I have a project where I need to add a 3rd dependent box. Sticking with the .additem way, how Shoukd I wrote the code to get box 2 items to box?

    Thank you so much! I’m struggle with the combinations.

  34. Bhupesh
    August 21, 2017 at 6:28 PM — Reply

    Hello Sir,

    I want to know how to make a combo box on a userform with search suggestions.

    The combox shall have items in it already from which i can choose one. However if the no. of items are too many , then in that case i may write the item name and its suggestion shall be reflected.
    like if i type ” Ram” in the combobox then i shall get the suggestion like ” Ramesh” & ” Ramalingam” etc.

    Kindly help me in this .

  35. Chirag Prajapati
    January 24, 2018 at 3:46 PM — Reply

    Hi…
    Thanks for your tutorial.
    I get one problem.
    After coding as above i get result but after closing excel sheet program need to run manually.
    It doesn’t work with auto run.

  36. LLY
    February 15, 2019 at 5:44 PM — Reply

    Hiya,

    Would it be possible to use Loop to identify a group of combo box? For example :

    For i = 1 to 10
    Sheets(“Sheet1”).combobox(i).List = Array(“Apple”, “Banana”, “Coconut”)
    next i

    Thank you

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Add values to a ComboBox in a UserForm in Excel.

There are 3 simple ways to add values, two that require VBA, and one that doesn’t require any programming at all.

(If you read the tutorial on how to add values to a ListBox, it is exactly the same as this tutorial and the same methods are used.)

Sections:

Where to Add Items for the ComboBox

Add Values to ComboBox — Method 1

Add Values to ComboBox — Method 2

Add Values to ComboBox — Method 3

Notes

Where to Add Items for the ComboBox

To add items to a ComboBox using Method 2 and Method 3 below, we have to use some VBA code and this code must go within the UserForm. Skip this section if you want to store the list in a worksheet in Excel and use Method 1.

Go to the VBA window (Alt + F11) and make sure you are viewing the Project window (Ctrl + R).

14654c2969abc539948d8ce152f1945b.png

Right-click over the desired UserForm and click View Code.

ba1e88ad4b75a30cda7f4c61b1aad039.jpg

In the window that opens, select UserForm from the left drop-down menu and Initialize from the right drop-down menu.

1b02247fdcaa7452ceb003604b25f511.jpg

Once you do this, you will see the code section UserForm_Initialize() like in the above image.

This is where the code goes, inbetween the two lines of code above.

The reason the code goes here is because this is the code that will run when the UserForm starts-up or opens and we want the ComboBox to be filled with the desired values immediately when the form opens.

If you already have the UserForm_Initialize section with code in it, just add the code for the ComboBox in the existing section.

Add Values to ComboBox — Method 1

Simple and requires no coding.

We create this list from a range of values in Excel. There is no coding required, so we don’t need to use any VBA or go to the Code window like in the last section.

Go to the VBA window (Alt + F11) > double-click the UserForm from the Project window (Ctrl + R if it’s not visible) and then, once the form is visible, click the ComboBox that you want to fill with values.

Look to the Properties window and scroll down to RowSource. If the Property window isn’t visible, hit F4.

57a909c176f8c28e4a31c85abfef1759.png

In there, enter the sheet and range reference to the list of data.

It is a good idea to include the sheet reference infront of the range, otherwise the ComboBox will assume the range is from the worksheet that you were on when you launched the UserForm.

In my example, the list is on sheet 1 in range G5 to G8: Sheet1!G5:G8

782f7cb6e09eb3553d25a3401d07a379.png

This is a very easy way to make and maintain a list for a ComboBox in Excel.

Tip: if you don’t want the user to be able to see or change this list, put it on a hidden worksheet.

Add Values to ComboBox — Method 2

Simple. Good for small lists. Requires VBA code — first section above explains where to put this code.

With ComboBox1
    .AddItem "Item 1"
    .AddItem "Item 2"
    .AddItem "Item 3"
    .AddItem "Item 4"
End With

ComboBox1 is the name of the ComboBox that we want to populate with data. The name of the ComboBox is found in the Properties window at the top and is called (Name).

.AddItem is what adds the value to the ComboBox.

Whatever you put inbetween the quotation marks after AddItem is what will be added to the list.

This method is cumbersome if you have a large list, but it is probably the most intuitive and easiest to understand.

Add Values to ComboBox — Method 3

More advanced, but not too difficult. Better for larger lists of items. Requires VBA code — first section above explains where to put this.

ComboBox1.List = Array("Item 1", "Item 2", "Item 3", "Item 4")

ComboBox1 is the name of the ComboBox that we will fill with values. The name of the ComboBox is found in the Properties window at the top and is called (Name).

.List adds the items from the array.

Array is the function that is used to create an array of the items for the list. If this seems confusing, don’t worry about it, just follow the syntax from the example above.

Note on Array Creation

This example uses an array to fill the list. There are many ways to create an array and some work better than others for long lists.

Here is an example that works like the last one, just with a little extra code so that we can build the array in a more visually intuitive manner, hopefully.

'Put values into an array
myArray = Split("Item 1;Item 2;Item 3;Item 4", ";")

'Add the array to the ComboBox
ComboBox1.List = myArray

We use the Split function to turn the values in the parenthesis into an array and we use a semi-colon to separate each item in the list.

The highlight of this version is that you don’t have to put quotation marks around every single item.

Notes

As you can see, there are a number of ways to add a list to a ComboBox. Choose whichever method works best for you!

Make sure to download the sample file for this tutorial to see these examples in Excel — note that the examples with code have been commented-out, simply remove the comment (single quotation mark) from the lines with the code to test out those methods.

Similar Content on TeachExcel

Add Values to a ListBox

Tutorial: How to fill a Listbox with values in a UserForm.
By default, a Listbox in a form will be e…

Dependent ComboBox Drop Down Menus

Tutorial: How to create UserForm drop-down menus that change based on what was selected in another d…

Put Data into a UserForm

Tutorial: How to take data from Excel and put it into a UserForm. This is useful when you use a form…

Add Text to UserForms and Labels

Tutorial: Multiple methods for adding text to a UserForm via a Label.
This includes a simple way to …

Multi-Column ComboBox Drop Down Menus in Forms

Tutorial: Multiple columns of data within a UserForm ComboBox drop-down menu in Excel.
I’ll show you…

Pass Values from One Macro to Another Macro

Tutorial:
How to pass variables and values to macros. This allows you to get a result from one macr…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

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

UserForm Controls — ComboBox and ListBox

———————————————————-

Contents:

Difference between ListBox and ComboBox

Key Properties of ComboBox and ListBox

Add Items/Data to (Populate) a ListBox or ComboBox

Extract ListBox & ComboBox Items, with VBA

Delete ListBox rows using the RemoveItem Method

———————————————————-

UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».

An Excel VBA ListBox or ComboBox is a list of items from which a user can select. They facilitate in accepting data from users and making entries in an Excel worksheet.

Difference between ListBox and ComboBox:

1. The ComboBox is a drop-down list (the user-entered item or the list-selected item is visible in the text area, whereas list values are visible by using the drop-down), while a ListBox shows a certain number of values with or without a scroll bar. In a ComboBox, only one row of items is visible at a given time (without using the drop-down) whereas in a ListBox one or more can be visible at a time.

2. In a ComboBox you can select ony one option from the list, while in a ListBox you can select multiple options from the list.

3. The user can enter his own item (in text area) in a ComboBox if it is not included in the list, which is not possible to do in a ListBox. In this sense, ComboBox is a combination of TextBox and ListBox.

4. CheckBox can be used within ListBox, but not within ComboBox. ListBox allows you to display a check box next to each item in the list, to enable user to select items (this might be easier for the user than using the multiple selection methods). To use CheckBoxes in a ListBox, set ListStyle property (in Properties Window)  to fmListStyleOption (vba code: ListBox1.ListStyle = fmListStyleOption). This setting is best used with a multiselect ListBox.

——————————————————————————————————————-

Key Properties of ComboBox and ListBox

Note1: All properties and methods given below are common to both ListBox and ComboBox, unless mentioned otherwise. Also refer «2. UserForm and Controls — Properties.» for properties common to the UserForm and most Controls.

Note 2: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.  

AddItem Method:

Adds an item to the list, in a single-column ListBox or ComboBox. Adds a row to the list (ie. an item for each row), in a multi-column ListBox or ComboBox. Syntax: Control.AddItem(Item, Index). Item specifies the item or row to add. Index is an Integer which specifies the position where the new item or row is placed within the list, and if omitted, the item or row is added at the end. The item or row numbers begin with zero, and the first item or row is numbered 0, and so on. The value of Index cannot be greater than the total number of rows (ie. value of ListCount property). AddItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. AddItem method can only be used with a macro or vba code. Note: AddItem method adds an item to the first column in a multi-column ListBox or ComboBox, and to add an item further to the first column, use the List or Column property specifying the item’s row and column number. More than one row can also be added at a time to a ListBox or ComboBox by using the List or Column properties (AddItem adds one row at a time). This means that you can copy a two-dimensional array of values to a ListBox or ComboBox, using List or Column properties rather than adding each individual element using the AddItem method. Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

BoundColumn Property:

Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1, second column has a value of 2, and so on. Setting the BoundColumn value to 1 will assign the value from column 1 to the ComboBox or ListBox, and so on. BoundColumn property lets the user to store a different set of values per specified column while TextColumn property displays one set of values, viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his height will get returned or stored (refer Image 10). The ColumnWidths property of a column can be set to zero to not display it in the ListBox. Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox). This setting is useful if you want to determine the row of the selected item in a ComboBox or ListBox. BoundColumn Property can be set in the Properties window and can also be used with a macro or vba code. Note: Where the ControlSource mentions =Sheet3!D2 (vba code: .ControlSource = «=Sheet3!D2»), the value in the BoundColumn of the selected row will get stored in cell D2, Sheet3.

Example 1: Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control  (in a Single Selection ListBox) — refer Image 7

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectSingle

.BoundColumn = 0

End With

End Sub

Private Sub CommandButton1_Click()
‘BoundColumn value is set as 0 which assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control. Note: MultiSelect Property is set to fmMultiSelectSingle which allows only single selection.

If ListBox1.Value <> «» Then

TextBox1.Value = ListBox1.Value + 2

End If

End Sub

Clear Method:

Removes all items in a ComboBox or ListBox. Syntax: Control.Clear. Clear method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. Clear method can only be used with a macro or vba code. 

Column Property:

Refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow). Column property can only be used with a macro or vba code and is not available at design time. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. iRow specifies the row number wherein iRow = 0 means the first row in the List. Both iColumn and iRow are integer values ranging from 0 to number of columns and rows (respectively) in the list minus 1. Specifying both column and row numbers will refer to a specific item, and specifying only the column number will refer to a specific column in the current row viz. ListBox1.Column(1) refers the second column. You can copy a two-dimensional array of values to a ListBox or ComboBox, using Column (or List) property rather than adding each individual element using the AddItem method. Column property can be used to assign the contents of a ComboBox or ListBox to another control, viz. TextBox (refer Image 8). Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

Example 2: Load ListBox using AddItem method and List & Column properties; and use Column property to assign the contents of ListBox to TextBox — refer Image 8

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.RowSource = «=Sheet2!A2:B6»

.MultiSelect = fmMultiSelectMulti

End With

‘clearing the TextBox if it is not empty
TextBox1 = «»

End Sub

Private Sub CommandButton1_Click()
‘Add items in ListBox using AddItem method to add new rows; use List & Column properties to add items in columns beyond the first column; and use Column property to assign the contents of ListBox to TextBox

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set
ListBox1.RowSource = «»

‘Create a new row with AddItem 

ListBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ListBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ListBox1.List(0, 2) = «day 2»

ListBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ListBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ListBox1.Column(2, 1) = «day 3»

‘Create a new row with AddItem and position as row number 1
ListBox1.AddItem «apple», 0

ListBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ListBox1.List(0, 2) = «day 1»

‘item in column number 3 and row number 2 of ListBox
TextBox1.Value = ListBox1.Column(2, 1)

End Sub

ColumnCount Property:

Specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns. ColumnCount property can be set in the Properties window and can also be used with a macro or vba code.

ColumnHeads Property:

A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox. ColumnHeads property can be set in the Properties window and can also be used with a macro or vba code. Column Headings can be displayed only if ColumnHeads is set to True in Properties window (VBA code: ListBox1.ColumnHeads = True) and if you bind the ListBox to a range (ie. set RowSource to a range that includes headings). Note: AddItem method will not work if ListBox or ComboBox is bound to data, hence RowSource property should be cleared for using AddItem.

List Property:

List Property is used in conjunction with the ListCount and ListIndex properties to return items in a ListBox or ComboBox control. Syntax -> Control.List(iRow,iCol). Each item in a list has a row number and a column number, wherein row and column numbers start with zero. iRow specifies the row number wherein iRow = 2 means the third row in the List. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. Omitting to specify the iColumn will retrieve the first column. Specify iColumn only for a multi-column ListBox or ComboBox. List Property can only be used with a macro or vba code and is not available at design time. Note: To copy a two-dimensional array of values to a ListBox or ComboBox, use List or Column properties. To add a one-dimensional array or to add an individual element, use the AddItem method. Items can be removed from a List using the RemoveItem method. List property is available only by using a macro or VBA.

Example 3: Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property — refer Image 9. 

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectMulti

.TextColumn = 1

End With

With TextBox1

.MultiLine = True

‘the text or value in the TextBox will get stored in the worksheet cell — Sheet3!F2
.ControlSource = «=Sheet3!F2»
‘if the cell Sheet3!F2 contains any text, this will not appear in the TextBox on initialization of UserForm
.Value = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property

TextBox1.Value = «»

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in TextBox
If ListBox1.Selected(n) = True Then

If TextBox1.Value = «» Then

‘ListBox1.List(n, 0) or ListBox1.List(n)displays the first column in TextBox, ListBox1.List(n, 1) displays the second column and so on
‘alternate code which displays the second column in TextBox: TextBox1.Value = Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value
TextBox1.Value = ListBox1.List(n, 1)

Else

‘alternate code which displays the second column in TextBox: TextBox1.Value = TextBox1.Value & vbCrLf & Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value

TextBox1.Value = TextBox1.Value & vbCrLf & ListBox1.List(n, 1)

End If

End If

Next n

End Sub

ListCount Property:

Determines the total number of rows in a ListBox or ComboBox. This property can only be used with a macro or vba code and is not available at design time. Note: The column headings row is also counted, if ColumnHeads are displayed. The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox.

ListIndex Property:

Determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on. Hence, it is an integer value ranging from 0 to the total number of items in a ComboBox or ListBox minus 1. ListIndex returns -1 when no rows are selected. This property can only be used with a macro or vba code and is not available at design time. Note: In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection.

ListRows Property:

Specifies the maximum number of rows which will display in the list box portion of a ComboBox. The default value is 8. Note: If the actual number of list items exceed this maximum value of the ListRows property, a vertical scroll bar will appear in the list box portion of the ComboBox (and the excess list items can be viewed by scrolling down). The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox. ListRows property can be set in the Properties window and can also be used with a macro or vba code. ListRows Property is valid for ComboBox and not for ListBox.

Example 4: Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox

Private Sub UserForm_Initialize()
‘this macro sets the ListRow value, on initialization of the UserForm

With ComboBox1

If .ListCount > 5 Then

.ListRows = 5

Else

.ListRows = .ListCount

End If

End With

End Sub

MultiSelect Property:

Specifies whether multiple selections are allowed. There are 3 settings: (i) fmMultiSelectSingle (value 0), the default setting, wherein only a single item can be selected; (ii) fmMultiSelectMulti (value 1) which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) fmMultiSelectExtended (value 2) which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection); this option also allows to select or deselect an item by pressing CTRL and clicking mouse. MultiSelect property can be set in the Properties window and can also be used with a macro or vba code. Note: MultiSelect Property is valid for ListBox and not for ComboBox. When multiple selections are made (viz. fmMultiSelectMulti or fmMultiSelectExtended), the selected items can be determined only by using the Selected property (Selected property is available by using macro) of the ListBox. The Selected property will have values ranging from 0 to ListCount minus 1 and will be True if the item is selected and False if not selected. The Selected property determines the items you chose, and the List property returns the items.

Example 5: Determining selected item in a Single Selection ListBox, in VBA:

Private Sub CommandButton1_Click()
‘determine and display selected item in a ListBox which allows only a single selection (viz. MultiSelect Property is set to fmMultiSelectSingle)
‘you can also determine selected item in a ListBox which allows only a single selection, by using the Selected Property (as used in a Multiple Selection enabled ListBox)

‘alternatively: If ListBox1.ListIndex >= 0 Then
If ListBox1.Value <> «» Then

MsgBox ListBox1.Value

End If

End Sub

RemoveItem Method:

A specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index is the row number which is specified to be removed, wherein the first row is numbered 0, and so on. RemoveItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. RemoveItem method can only be used with a macro or vba code.

RowSource Property:

Specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox. RowSource property can be set in the Properties window and can also be used with a macro or vba code. To set RowSource property in Properties window, enter without inverted commas: «=Sheet2!A2:A6» which populates ComboBox or ListBox with values in cells A2:A6 in Sheet2. VBA code for this is: ListBox1.RowSource = «=Sheet2!A2:A6». It is not necessary to use the equal mark in «=Sheet2!A2:A6» while setting the property and ListBox1.RowSource = «Sheet2!A2:A6» will have the same effect.

Selected Property:

Specifies whether an item is selected in a ListBox control. Syntax: Control.Selected(Item_Index). Returns True/False if the item is Selected/NotSelected; Set to True/False to select the item or remove selection [viz. Control.Selected(ItemIndex) = True/False]. Item_Index is an integer value ranging from 0 to number of items in the list minus 1, indicating its relative position in the list, viz. ListBox.Selected(2) = True selects the third item in the list. Selected property is particularly useful when working with multiple selections. Selected Property can only be used with a macro or vba code and is not available at design time. Note1: In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection. Note2: Selected Property is valid for ListBox and not for ComboBox.

Example 6: Determining selected items in a multiple-selection enabled ListBox using Selected & List properties:

Private Sub CommandButton1_Click()
‘display all selected items in a ListBox using the Selected property (valid for a ListBox with MultiSelect Property setting of either single-selection or multiple-selection)

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in MsgBox

If ListBox1.Selected(n) = True Then

‘display a selected item
MsgBox ListBox1.List(n)

End If

Next n

End Sub

Style Property:

Valid for ComboBox only, not for ListBox. This property determines choosing or setting the value of ComboBox. There are 2 settings: (i) fmStyleDropDownCombo (value 0). The user has both options of typing a custom value in the text area or select from the drop-down list. This is the default value.; (ii) fmStyleDropDownList (value 2). The user can only select from the drop-down list, like in ListBox. Style Property can be set in the Properties window and can also be used with a macro or vba code.

TextColumn Property:

Specifies the column of data in a ListBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value property if the TextColumn property is not set. First column has a TextColumn value of 1, second column has a value of 2, and so on. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property) viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his name & height will be returned. The ColumnWidths property of any column can be set to zero to not display it in the ListBox. Setting the TextColumn value to 0 displays the ListIndex value (which is the number of the selected row) in TextColumn Property — this setting is useful if you want to determine the row of the selected item. TextColumn property can be set in the Properties window and can also be used with a macro or vba code. Note: In a ComboBox, when a user selects an item, the column specified in the TextColumn property will be displayed in the ComboBox’s text box portion.

Example 7: Display first column in the List and use the TextColumn & BoundColumn Properties to return values from first & third columns (in a Single Selection ListBox) — refer Image 10

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 3

‘set the ColumnWidths property of second & third columns to zero to not display them in the ListBox

.ColumnWidths = «40;0:0»

.RowSource = «=Sheet2!A2:C6»

.MultiSelect = fmMultiSelectSingle

‘specifies the column of data in a ListBox that supplies data for its Text property

.TextColumn = 1

.BoundColumn = 3

End With

End Sub

Private Sub CommandButton1_Click()
‘TextColumn value is set as 1 and BoundColumn value is set as 3.

‘works only if MultiSelect Property of ListBox is set to fmMultiSelectSingle which allows single selection.
If ListBox1.Value <> «» Then   

‘use the ListBox Text property to return the value from the column specified in the TextColumn column, whereas the ListBox Value property returns the value from the column specified in the BoundColumn property

TextBox1.Value = ListBox1.Text & » — » & ListBox1.Value & » cms»

End If

End Sub

———————————————————————————————————————  

Add Items/Data to (Populate) a ListBox or ComboBox

1. Setting the RowSource property of a ListBox or ComboBox in a UserForm

VBA code — if the list is static:

Me.ListBox1.RowSource = «Sheet1!A1:B6»

or
Me.ListBox1.RowSource = «=Sheet1!A1:B6»

VBA code — if the list is dynamic:

Me.ListBox1.RowSource = «Sheet1!A1:B» & Sheet1.Cells(Rows.Count, «B»).End(xlUp).Row

Note: You can set the RowSource property of a ListBox or ComboBox in the Properties Window (without using vba code), by entering -> Sheet1!A1:B6

Example 8: Populate ComboBox by setting the RowSource property to a named list — refer Image 11

Private Sub UserForm_Initialize()
‘populate ComboBox by setting the RowSource property to a named list

With ComboBox1

.ColumnCount = 2

.ColumnWidths = «50;50»

.ColumnHeads = True

‘For a named list (viz. “HeightList” in Range A2:B6), the RowSource property can be set to Sheet1!HeightList

.RowSource = «Sheet1!HeightList»

End With

End Sub

2. Populate a ComboBox or ListBox from an Array:

VBA code — populate single column in ListBox:

ListBox1.List = Array(«RowOne», «RowTwo», «RowThree», «RowFour»)

VBA code — populate single column in ComboBox:

ComboBox1.List = Array(«Apples», «Bananas», «Oranges», «Pears»)

VBA code — populate ListBox from array named myArray:

Dim myArray As Variant
myArray = Array(«Adidas», «Nike», «Reebok»)
Me.ListBox1.List = myArray

VBA code — Populate single column ComboBox:

Dim i As Integer
Dim myArray As Variant

myArray = Array(«Adidas», «Nike», «Reebok», «Puma», «Polo»)

    For i = LBound(myArray) To UBound(myArray)

Me.ComboBox1.AddItem myArray(i)

Next

Example 9 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox

Dim rng As Range

Set rng = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = rng.Cells.Value

End Sub

Example 10 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox:

Dim var As Variant

var = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = var

End Sub

Example 11: Load Worksheet Range to a multi-column ListBox, after placing Range data in a 2-dimensional Array — refer Image 12

Option Base 1
——————————————
Private Sub UserForm_Initialize()
‘Load Worksheet Range to a ListBox, after placing data in an Array

Dim rng As Range
Dim cell As Range
Dim totalRows As Integer, totalColumns As Integer
Dim iRow As Integer, iCol As Integer
Dim myArray() As Variant

Set rng = Sheet1.Range(«A1:C6»)
totalRows = Sheet1.Range(«A1:C6»).Rows.Count
totalColumns = Sheet1.Range(«A1:C6»).Columns.Count

‘if Option Base 1 was not set, this line of code should be: ReDim myArray(1 To totalRows, 1 To totalColumns)
ReDim myArray(totalRows, totalColumns)

‘place worksheet range data in an Array:
For Each cell In rng

For iRow = 1 To totalRows

For iCol = 1 To totalColumns

myArray(iRow, iCol) = rng.Cells(iRow, iCol)

Next iCol

Next iRow

Next

‘set ListBox properties and load Array to ListBox

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.List = myArray

End With

End Sub

Example 12: Load a 2-dimensional array to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array) — refer Image 13

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

With ListBox2

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

End Sub

Private Sub CommandButton1_Click()
‘create a 2-dimensional array and load to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array)

‘Declaring the array and its dimensions. The array has been named myArray, of size 3 by 3 (three rows by three columns). Note: When you populate an array with data, the array will start at zero, and if you include Option Base 1 the array will start at 1.
Dim myArray(3, 3)

‘populate column 1 of myArray, with numbers

For n = 0 To 2

myArray(n, 0) = n + 1

Next n

‘populate column 2 of myArray
myArray(0, 1) = «R1C2»
myArray(1, 1) = «R2C2»
myArray(2, 1) = «R3C2»

‘populate column 3 of myArray
myArray(0, 2) = «R1C3»
myArray(1, 2) = «R2C3»
myArray(2, 2) = «R3C3»

‘copy data to ListBox1 (using List property) and ListBox2 (using Column property):

‘copies an array without transposing it
ListBox1.List() = myArray
‘transposes the contents of the array
ListBox2.Column() = myArray

End Sub

3. Populate a ComboBox or ListBox with AddItem method

Example 13: Populate a single-column ListBox from worksheet range

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populating a single-column ListBox with AddItem method
Dim cell As Range
Dim rng As Range

    
Set rng = Sheet1.Range(«A1:A6»)

For Each cell In rng.Cells

Me.ListBox1.AddItem cell.Value

Next cell

End Sub

Example 14: Populate a single-column ListBox with values from 1 to 500

Private Sub UserForm_Initialize()
‘set ListBox properties on activation of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populate a single-column ListBox with values from 1 to 500, and «N/A»
With ListBox1

.AddItem «N/A»

For i = 1 To 500

.AddItem i

Next i

End With

End Sub

Example 15: Create a new row with AddItem and specify its row number — refer Image 14

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘using AddItem method to populate single-column ListBox:
ListBox1.AddItem «banana»
ListBox1.AddItem «orange»

‘Create a new row with AddItem and position as row number 1 — this will push down the above two rows
ListBox1.AddItem «apple», 0
‘Create a new row with AddItem and position as row number 2 — this will push down the above two rows to no. 3 and 4
ListBox1.AddItem «pears», 1

End Sub

Example 16: Populate a ComboBox with the 12 months in a year — Refer Image 15

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populates ComboBox with the 12 months in a year

For n = 1 To 12

ComboBox1.AddItem Format(DateSerial(2011, n, 1), «mmmm»)

Next n

End Sub

4. Populate a multi-column ComboBox or ListBox using AddItem method and List & Column properties

Example 17:  refer Image 16

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘Populating a multi-column ListBox using AddItem method and List & Column properties:

‘Create a new row with Additem
ComboBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ComboBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ComboBox1.List(0, 2) = «day 2»

ComboBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ComboBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ComboBox1.Column(2, 1) = «day 3»

‘Create a new row with Additem and position as row number 1
ComboBox1.AddItem «apple», 0
ComboBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ComboBox1.List(0, 2) = «day 1»

End Sub

5. Populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Example 18:  refer Image 17

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Dim counter As Long
Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet4.Cells(Rows.Count, «A»).End(xlUp).Row
counter = 0

‘ListBox gets populated with all rows in column A:
Do

With Me.ListBox1

counter = counter + 1

‘create a new row with Additem
.AddItem Sheet4.Cells(counter, 1).Value
‘add item in second column of a row
.List(.ListCount — 1, 1) = Sheet4.Cells(counter, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet4.Cells(counter, 1).Offset(0, 2).Value

End With

Loop Until counter = totalRows

End Sub

6. Add a new item/row to the list if ComboBox is bound to data in a worksheet. 

Example 19: refer Images 18a & 18b

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

‘a named-range (name: «cbRange») has been created in Sheet3 of the workbook, using the Name Manager: «=Sheet3!$A$2:$C$6»

.RowSource = «cbRange»

End With

End Sub

Private Sub CommandButton1_Click()
‘add a new item/row to the list if ComboBox is bound to data in a worksheet

Dim colNo As Long

‘determine first column of the named-range «cbRange»
colNo = Range(«cbRange»).Column

‘create a new single-column named-range (name: «cbRangeTemp»), populated with only the first column of the named-range «cbRange».
Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count, 1).Name = «cbRangeTemp»

‘checks if ComboBox1.Value is already existing in column 1 of named-range «cbRange»
If Application.CountIf(Range(«cbRangeTemp»), ComboBox1.Value) = 0 Then

‘resizing the named-range «cbRange», to add another worksheet row at the end, wherein the ComboBox1.Value will get posted:

Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count + 1).Name = «cbRange»

ComboBox1.RowSource = «cbRange»

‘posting columns of the new row with values from ComboBox1, TextBox1 & TextBox2:

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo) = ComboBox1.Value

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 1) = TextBox1.Text

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 2) = TextBox2.Text

Else

MsgBox «Item already in List»

End If

ComboBox1.Value = «»
TextBox1.Text = «»
TextBox2.Text = «»

End Sub

——————————————————————————————————————————————-  

Extract ListBox & ComboBox Items, with VBA

VBA code — Display selected ComboBox item in TextBox:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item gets displayed in TextBox

TextBox1.Value = ComboBox1.Value

Note: VBA code-> TextBox1.Value = ListBox1.Value, or TextBox1.Text = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy selected ComboBox item to a worksheet range:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item is copied to the worksheet range

Sheet1.Range(«G4»).Value = ComboBox1.Value

Note: VBA code-> Sheet4.Range(«G4»).Value = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy ComboBox item determined by its position, to a worksheet range:

‘an existing ComboBox item, determined by its position (row 4, column 1), posted to a worksheet cell

Sheet1.Range(«F2»).Value = ComboBox1.List(3, 0)

Note: VBA code for ListBox -> Sheet1.Range(«F2»).Value = ListBox1.List(3, 0)

Example 20: Extracting ListBox items (of multi-column ListBox) to a worksheet range — refer Image 19

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.RowSource = «Sheet2!A2:C6»

.MultiSelect = fmMultiSelectMulti

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to copy multiple-selected ListBox items (of multi-column ListBox) to a worksheet range

‘check all items/rows in a ListBox
For r = 0 To ListBox1.ListCount — 1

‘if a ListBox row is selected, it will get copied to the worksheet range

If ListBox1.Selected(r) = True Then

‘copying multi-column ListBox rows to corresponding/matching worksheet rows & columns:

For c = 1 To ListBox1.ColumnCount

Sheet1.Cells(r + 1, c).Value = ListBox1.List(r, c — 1)

Next c

End If

Next r

End Sub

Example 21: Extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range — refer Image 20

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

.MultiSelect = fmMultiSelectSingle

.RowSource = «Sheet3!A2:C6»

End With

End Sub

Private Sub CommandButton1_Click()
‘extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range
‘ListIndex property is used to return and set a selection in a single-selection ListBox, but not in a multi-selection ListBox
‘ListBox1.Value will work only in case of a single-selection ListBox. It will copy the selected item (value in BoundColumn) from the list.

Dim rng As Range
Set rng = Sheet3.Cells(9, 1)

    
If ListBox1.Value <> «» Then

rng.Value = ListBox1.Value

rng.Offset(0, 1).Value = ListBox1.List(ListBox1.ListIndex, 1)

rng.Offset(0, 2).Value = ListBox1.List(ListBox1.ListIndex, 2)

End If

    
End Sub

Example 22: Select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — refer Image 21

Private Sub UserForm_Initialize()
‘set comboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = True

.RowSource = «Sheet3!A2:B6»

End With

‘disallow manual entry in TextBox

With TextBox1

.Enabled = False

End With

End Sub

Private Sub CommandButton1_Click()
‘select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — use ComboBox, TextBox & CheckBox properties and worksheet functions Vlookup and Countif

Dim totalRows As Long

‘determine total number of rows in column B
totalRows = Sheet3.Cells(Rows.Count, «B»).End(xlUp).Row

Me.ComboBox1.ControlTipText = «Select Name»
Me.CommandButton1.ControlTipText = «Click to get Grade»

‘Name selected in ComboBox is posted to TextBox
TextBox1.Text = ComboBox1.Value

‘Grade will be searched only if a name is selected and the CheckBox is selected:
If CheckBox1 = True And TextBox1.Text <> «» Then

‘check if name selected or entered in ComboBox is present in the lookup range:

If Application.CountIf(Sheet3.Range(«A1:A» & totalRows), TextBox1.Text) > 0 Then

‘lookup Grade of selected Name, in the worksheet range

Sheet3.Cells(1, 4).Value = TextBox1.Text & «‘s grade is » & Application.VLookup(TextBox1.Text, Sheet3.Range(«A1:B» & totalRows), 2, False)

Else

MsgBox «Name not found!»

End If

End If

End Sub

——————————————————————————————————————————————-  

Delete ListBox rows using the RemoveItem Method

Example 23: Use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet — refer Images 22a and 22b.

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.MultiSelect = fmMultiSelectMulti

End With

Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet3.Cells(Rows.Count, «A»).End(xlUp).Row

‘load a dynamic worksheet range to a ListBox
Dim rng As Range
Set rng = Sheet3.Range(«A2:C» & totalRows)
Me.ListBox1.List = rng.Cells.Value

‘removes all items in ListBox
‘ListBox1.Clear

End Sub

Private Sub CommandButton1_Click()
‘use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet

Dim n As Long, i As Long
Dim var As Variant

‘deleting row from ListBox using RemoveItem method:

‘check all items in a ListBox; reverse order (Step -1) is used because rows are being deleted from ListBox.
For n = ListBox1.ListCount — 1 To 0 Step -1

If ListBox1.Selected(n) = True Then

‘item to be deleted is stored in the variable named var

var = ListBox1.List(n, 0)
ListBox1.RemoveItem (n)

‘determine row number in which items are to be deleted; Note: value of variable named var is derived from first column, hence Range(«A:A») is searched in the Match formula.
i = Application.Match(var, Sheet3.Range(«A:A»), 0)

‘delete all 3 columns of the determined row in the worksheet:
Sheet3.Cells(i, 1) = «»

Sheet3.Cells(i, 1).Offset(0, 1) = «»
Sheet3.Cells(i, 1).Offset(0, 2) = «»

‘use this code instead of the preceding 3-lines, to delete the determined row in the worksheet
‘Sheet3.Rows(i).Delete

End If

Next n

End Sub

Example 24: Delete all rows in ListBox, using RemoveItem method

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.BoundColumn = 1

.MultiSelect = fmMultiSelectMulti

‘RemoveItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

ListBox1.RowSource = «»

End With

For n = 2 To 6

With Me.ListBox1

‘create a new row with Additem

.AddItem Sheet3.Cells(n, 1).Value
‘add item in second column of a row

.List(.ListCount — 1, 1) = Sheet3.Cells(n, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet3.Cells(n, 1).Offset(0, 2).Value

End With

Next n

End Sub

Private Sub CommandButton1_Click()
‘delete all rows in ListBox, using RemoveItem method

Dim n As Integer

For n = 1 To ListBox1.ListCount

‘Note: «ListBox1.RemoveItem 0» is the same as «ListBox1.RemoveItem (0)»

‘alternate code: ListBox1.RemoveItem 0

ListBox1.RemoveItem ListBox1.ListCount — 1

Next n

End Sub

Like this post? Please share to your friends:
  • Excel vba is value in array
  • Excel vba number from string
  • Excel vba is nothing is not nothing
  • Excel vba number format number
  • Excel vba is not numeric