Excel vba listbox controlsource

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

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

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

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

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

Элемент управления ListBox позволяет выбрать несколько позиций из списка, но эта возможность не имеет практического смысла. Ввести информацию в ListBox с помощью клавиатуры или вставить из буфера обмена невозможно.

Свойства списка

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

* При Enabled в значении False возможен только вывод информации в список для просмотра.
** Для элемента управления ListBox действие свойства Locked в значении True аналогично действию свойства Enabled в значении False.
*** Если включен многострочный выбор, свойства Text и Value всегда возвращают значения по умолчанию (пустая строка и Null).

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

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

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

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

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

With UserForm1.ListBox1

  .AddItem «Значение 1»

  .AddItem «Значение 2»

  .AddItem «Значение 3»

End With

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

UserForm1.ListBox1.List = Array(«Текст 1», _

«Текст 2», «Текст 3», «Текст 4», «Текст 5»)

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

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

UserForm1.ListBox1.RowSource = «Лист1!A1:A6»

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

With UserForm1.ListBox1

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

  .ColumnCount = 5

  .RowSource = «‘Лист со списком’!A1:E10»

End With

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

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

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

Для привязки списка к ячейке на рабочем листе используется свойство ControlSource. Суть привязки заключается в том, что при выборе строки в элементе управления, значение свойства Value копируется в привязанную ячейку.

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

В случае, когда при открытии формы в привязанной к списку ячейке содержится значение, которого нет ни в одной из строк элемента управления ListBox, будет сгенерирована ошибка.

Привязать ячейку к списку можно, указав адрес ячейки в поле свойства ControlSource в окне Properties элемента управления ListBox. Или присвоить адрес ячейки свойству ControlSource в коде VBA Excel:

UserForm1.ListBox1.ControlSource = «Лист1!A2»

Теперь значение выбранной строки в списке автоматически копируется в ячейку «A2» на листе «Лист1»:

Элемент управления ListBox с привязанной ячейкой

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

Извлечение информации из списка

Первоначально элемент управления ListBox открывается со строками, ни одна из которых не выбрана. При выборе (выделении) строки, ее значение записывается в свойства Value и Text.

Из этих свойств мы с помощью кода VBA Excel извлекаем информацию, выбранную в списке пользователем:

Dim myVar as Variant, myTxt As String

myVar = UserForm1.ListBox1.Value

‘или

myTxt = UserForm1.ListBox1.Text

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

Если ни одна позиция в списке не выбрана, свойство Value возвращает значение Null, а свойство Text – пустую строку. Если выбрана строка в многостолбцовом списке, в свойства Value и Text будет записана информация из первого столбца.

Что делать, если понадобятся данные из других столбцов многостолбцового списка, кроме первого?

Для получения данных из любого столбца элемента управления ListBox используется свойство List, а для определения выбранной пользователем строки – ListIndex.

Для тестирования приведенного ниже кода скопируйте таблицу и вставьте ее в диапазон «A1:D4» на листе с ярлыком «Лист1»:

Звери Лев Тапир Вивера
Птицы Грач Сорока Филин
Рыбы Карась Налим Парусник
Насекомые Оса Жук Муравей

Создайте в редакторе VBA Excel пользовательскую форму и добавьте на нее список с именем ListBox1. Откройте модуль формы и вставьте в него следующие процедуры:

Private Sub UserForm_Initialize()

With Me.ListBox1

  ‘Указываем, что у нас 4 столбца

  .ColumnCount = 4

  ‘Задаем размеры столбцов

  .ColumnWidths = «50;50;50;50»

  ‘Импортируем данные

  .RowSource = «Лист1!A1:D4»

  ‘Привязываем список к ячейке «F1»

  .ControlSource = «F1»

End With

End Sub

Private Sub UserForm_Click()

MsgBox Me.ListBox1.List(Me.ListBox1.ListIndex, 2)

End Sub

В процедуре UserForm_Initialize() присваиваем значения некоторым свойствам элемента управления ListBox1 перед открытием пользовательской формы. Процедура UserForm_Click() при однократном клике по форме выводит в MsgBox значение из третьего столбца выделенной пользователем строки.

Результат извлечения данных из многостолбцового элемента управления ListBox

Теперь при выборе строки в списке, значение свойства Value будет записываться в ячейку «F1», а при клике по форме функция MsgBox выведет значение третьего столбца выделенной строки.

Обратите внимание, что при первом запуске формы, когда ячейка «F1» пуста и ни одна строка в ListBox не выбрана, клик по форме приведет к ошибке. Это произойдет из-за того, что свойство ListIndex возвратит значение -1, а это недопустимый номер строки для свойства List.

Если для списка разрешен многострочный выбор (MultiSelect = fmMultiSelectMulti или MultiSelect = fmMultiSelectExtended), тогда, независимо от количества выбранных строк, свойство Value будет возвращать значение Null, а свойство Text – пустую строку. Свойство ListIndex будет возвращать номер строки, которую кликнули последней, независимо от того, что это было – выбор или отмена выбора.

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

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

Содержание

  1. Свойство ControlSource
  2. Синтаксис
  3. Замечания
  4. См. также
  5. Поддержка и обратная связь
  6. ListBox.ControlSource property (Access)
  7. Syntax
  8. Remarks
  9. Example
  10. Support and feedback
  11. VBA Excel. Элемент управления ListBox (список)
  12. Элемент управления ListBox
  13. Свойства списка
  14. Способы заполнения ListBox
  15. Свойство ListBox.ControlSource (Access)
  16. Синтаксис
  17. Замечания
  18. Пример
  19. Поддержка и обратная связь
  20. VBA Listbox – A Complete Guide
  21. What is the VBA ListBox used for?
  22. VBA ListBox versus the VBA ComboBox
  23. The VBA ListBox Properties Quick Guide
  24. How to Add Items to the ListBox
  25. VBA ListBox List Property
  26. The List Property and Column Headers
  27. Updating Items using the List Property
  28. VBA ListBox RowSource
  29. How to use RowSource
  30. RowSource Column Headers
  31. VBA ListBox AddItem
  32. VBA ListBox Selected Items
  33. Reading Data from the VBA Listbox
  34. Single selection only with one column
  35. Single selection only with multiple columns
  36. Multiple selections
  37. VBA ListBox MultiSelect
  38. VBA ListBox Columns
  39. VBA ListBox Column Headers
  40. Creating a ListBox Dynamically
  41. Loop through ListBoxes
  42. YouTube Video
  43. What’s Next?
  44. 34 Comments

Свойство ControlSource

Указывает расположение даты, использованной для задания или хранения свойства Value элемента управления. Свойство ControlSource принимает диапазоны листа из Microsoft Excel.

Синтаксис

object. ControlSource [= String ]

Синтаксис свойства ControlSource состоит из следующих частей:

Part Описание
object Обязательно. Допустимый объект.
String Необязательный параметр. Задает ячейку листа, связанную со свойством Value элемента управления.

Замечания

Свойство ControlSource указывает ячейку или поле; оно не содержит данные, хранящиеся в этом поле или ячейке. Если вы изменяете свойство Value элемента управления, это изменение автоматически отображается в связанной ячейке или поле. Аналогичным образом, если изменяется значение связанной ячейки или поля, это изменение автоматически отображается в свойстве Value элемента управления.

Невозможно задать другой элемент управления для свойства ControlSource. Это действие вызывает ошибку.

Значением по умолчанию для свойства ControlSource является пустая строка. Если свойство ControlSource содержит значение, отличное от пустой строки, оно указывает связанную ячейку или поле. Содержимое этой ячейки или поля автоматически копируется в свойство Value при загрузке элемента управления.

Если свойство Value имеет значение Null, в расположении, указанном свойством ControlSource, значение отсутствует.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

ListBox.ControlSource property (Access)

Use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. Read/write String.

Syntax

expression.ControlSource

expression A variable that represents a ListBox object.

The ControlSource property uses the following settings.

Setting Description
A field name The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field. (To make the control read-only, set the Locked property to Yes.)

If you choose a control bound to a field that has a Hyperlink data type, you jump to the destination specified in the hyperlink address.

An expression The control displays data generated by an expression. This data can be changed by the user but isn’t saved in the database.

For reports, the ControlSource property applies only to report group levels.

Forms and reports act as «windows» into your database. You specify the primary source of data for a form or report by setting its RecordSource property to a table, query, or SQL statement. You can then set the ControlSource property to a field in the source of data or to an expression.

If the ControlSource property setting is an expression, the value displayed is read-only and not saved in the database. For example, you can use the following settings.

Sample setting Description
LastName For a control, data from the LastName field is displayed in the control. For a report group level, Microsoft Access groups the data on last name.
=Date( ) + 7 For a control, this expression displays a date seven days from today in the control.
=DatePart(«q»,ShippedDate) For a control, this expression displays the quarter of the shipped date. For a report group level, Access groups the data on the quarter of the shipped date.

Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City.

The following example sets the ControlSource property for a text box named Expected to the expression =Date() + 7 .

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Excel. Элемент управления ListBox (список)

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

Элемент управления ListBox

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

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

Элемент управления ListBox позволяет выбрать несколько позиций из списка, но эта возможность не имеет практического смысла. Ввести информацию в ListBox с помощью клавиатуры или вставить из буфера обмена невозможно.

Свойства списка

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

* При Enabled в значении False возможен только вывод информации в список для просмотра.
** Для элемента управления ListBox действие свойства Locked в значении True аналогично действию свойства Enabled в значении False.
*** Если включен многострочный выбор, свойства Text и Value всегда возвращают значения по умолчанию (пустая строка и Null).

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

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

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

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

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

Источник

Свойство ListBox.ControlSource (Access)

Используйте свойство ControlSource, чтобы указать, какие данные отображаются в элементе управления. Вы можете отображать и изменять данные, привязанные к полю в таблице, запросе или инструкции SQL. Вы также можете отобразить результат выражения. Для чтения и записи, String.

Синтаксис

expression. ControlSource

Выражение Переменная, представляющая объект ListBox .

Замечания

Свойство ControlSource использует следующие параметры.

Setting Описание
Имя поля Элемент управления привязан к полю в таблице, запросе или инструкции SQL. Данные из поля отображаются в элементе управления . Изменения данных внутри элемента управления изменяют соответствующие данные в поле . (Чтобы сделать элемент управления только для чтения, задайте для свойства Locked значение Да.)

При выборе элемента управления, привязанного к полю с типом данных Гиперссылка, вы перейдете к назначению, указанному в адресе гиперссылки.

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

Для отчетов свойство ControlSource применяется только к уровням группы отчетов.

Формы и отчеты выступают в качестве «окон» в вашей базе данных. Вы можете указать основной источник данных для формы или отчета, задав для свойства RecordSource таблицу, запрос или инструкцию SQL. Затем можно задать для свойства ControlSource поле в источнике данных или выражение.

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

Пример параметра Описание
LastName Для элемента управления в элементе управления отображаются данные из поля LastName . На уровне группы отчетов Microsoft Access группировать данные по фамилии.
=Date( ) + 7 Для элемента управления это выражение отображает в элементе управления дату через семь дней с сегодняшнего дня.
=DatePart(«q»,ShippedDate) Для элемента управления это выражение отображает четверть даты отправки. На уровне группы отчетов Access группируют данные за квартал даты отправки.

Пример

В следующем примере свойство ControlSource для текстового поля с именем AddressPart задается в поле City.

В следующем примере свойство ControlSource для текстового поля с именем Expected задается для выражения =Date() + 7 .

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Listbox – A Complete Guide

The VBA ListBox is a very useful control. If you are creating any kind of UserForm application you will most likely use it.

In this post, I’m going to show you everything you need to know about the VBA ListBox so you can avoid the common pitfalls and get up and running quickly and easily.

What is the VBA ListBox used for?

The ListBox is used to display a list of items to the user so that the user can then select one or more. The ListBox can have multiple columns and so it is useful for tasks like displaying records.

VBA ListBox versus the VBA ComboBox

The ListBox is very similar to the ComboBox which also allows the user to select an item from a list of items. The main differences are:

  1. The Listbox allows multiple selections. The Combobox only allows one selection.
  2. Items in the ListBox are always visible. The Combobox items are only visible when you click on the “down” icon.
  3. The ComboBox has the ability to filter the contents when you type.

The VBA ListBox Properties Quick Guide

Function Operation Example
AddItem Add an item listbox.AddItem «Spain»
Clear Remove all Items listbox.Clear
ColumnCount Set the number of visible columns ComboBox1.ColumnCount = 2
ColumnHeads Make the column row visible ComboBox1.ColumnHeads = True
List Range to Listbox
ListBox to Range
Listbox.List = Range(«A1:A4»).Value
Range(«A1:A4»).Value = Listbox.List
List Update a column value Listbox.List(1,2) = «New value»
ListCount Get the number of items cnt = listbox.ListCount
ListIndex Get/set selected item Idx = listbox.ListIndex
combo.ListIndex = 0
RemoveItem Remove an item listbox.Remove 1
RowSource Add a range of values from a worksheet ComboBox1.RowSource = Sheet1.Range( «A2:B3» ).Address
Value Get the value of selected Item Dim sCountry As String
sCountry = listbox.Value

How to Add Items to the ListBox

There are 3 ways to add items to the VBA Listbox:

  1. One at a time using the AddItem property.
  2. Adding an array/range using the List property.
  3. Adding a Range using the RowSource property.

The List and RowSource properties are the most commonly used. The table below provides a quick comparison of these properties:

Task RowSource List
Column Headers Yes No
Update values in ListBox No Yes
Add new items No Yes
Data type Range Array(including Range.Value)
If source data changes Listbox is automatically updated. ListBox is not updated.

VBA ListBox List Property

The List property allows you to add to contents of an array to a ListBox. As Range.Value is an array you can copy the contents of any range to the Listbox.

Here are some examples of using the List property:

You can also use the List property to write from the ListBox to an array or range:

Important Note: If there is only one item in a range then VBA doesn’t covert it to an array. Instead, it converts the range to a string/double/date etc.

In this case, you need to use AddItem to add the value to the ListBox:

The List Property and Column Headers

The ListBox only displays column headers if you use RowSource . Otherwise, they are not available. The best way to add column headers(and it’s not a great way) is to add Labels above the ListBox columns. One advantage is that you can use the click event of the Label if you want to implement something like sorting.

Updating Items using the List Property

You can update individual items in the ListBox using the List Property.

Imagine we have a ListBox with data like this:

If we want to change Nelson in row 3, column 2 we do it like this:

The result we get is:

The List property rows and columns are zero-based so this means row 1 is 0, row 2 is 1, row 3 is 2 and so on:

VBA ListBox RowSource

The RowSource property allows us to add a range to the ListBox. This is different from the List Property in that the Range is linked to the ListBox. If data in the Range changes then the data in the ListBox will update automatically.

When we use RowSource the data in the ListBox is read-only. We can change the RowSource range but we cannot change the values in the ListBox.

How to use RowSource

We add the RowSource range as a string like this:

If you don’t specify the sheet the VBA will use the active sheet

If you are using the Address of a range object with RowSource then it is important to use the External parameter. This will ensure that RowSource will read from the sheet of the range rather than the active sheet:

RowSource Column Headers

Column headers are automatically added to the ListBox when you use the RowSource property. The ColumnHeads property must be set to True or the headers will not appear. You can set this property in the code or in the properties window of the ListBox.

The column headers are taken from the row above the range used for the RowSource . For example, if your range is A2 to C5 then the column header will use the range A1 to C1:

Here is an example: We want to add the data below to our ListBox and we want A1 to C1 to be the header.

We set the RowSource property to A2:C5 and set the ColumnHeads property to true:

The result will look like this:

VBA ListBox AddItem

It is very rare that you would use the AddItem property to fill the ListBox. List and RowSource are much more efficient. AddItem is normally used when the Listbox already has items and you want to add a new item.

The AddItem property is simple to use. You provide the item you want to add as a parameter. The ListBox will automatically add it as the last item:

If you want to Insert the item at a certain position you can use the second parameter. Keep in mind that this is a zero-based position, so if you want the item in position one then the value is 0, position 2 the value is 1, and so on.

The order will be:
Banana
Apple
Orange

If you want to add multiple columns with AddItem then you need to use the List property after you use AddItem:

One reason for using AddItem is if you are adding from data that isn’t sequential so you cannot use the List or RowSource properties:

Important Note: If you fill a ListBox with RowSource then you cannot use AddItem to add a new item. If you try you will get a “Runtime Error 70 – Permission Denied”.

VBA ListBox Selected Items

If only one item is selected then you can use ListIndex to get the selected row. Remember that it is zero-based so row 1 in the ListBox is at ListIndex 0, row 2 at ListIndex 1 and so on.

If the ListBox has multiple columns then you can use the ListIndex and List properties together to return a value in the selected row:

If multiple items are selected then you can use the GetSelectedRows function which returns a collection of selected rows:

Reading Data from the VBA Listbox

To read data from the ListBox we can use the ListBox.Value property. This only works when the ListBox is set to only select one item i.e. MultiSelect is set to frmMultiSelectSingle(see the section VBA ListBox MultiSelect below for more about this).

Single selection only with one column

When only one item is selected we can use the Value property to get the currently selected item:

Keep in mind that if there are multiple columns, Value will only return the value in the first column.

Single selection only with multiple columns

If the ListBox has Multiple columns you can use the Value property to get the value in the first column. You need to read through the List property to get the values in the other column(s). The List property is essentially an array so you can treat it like one.

In the example below we read through the columns of row 1(the index of row 1 is 0):

Normally you want to print the values in the selected row. You can use the ListIndex property to get the selected item(Note that ListIndex returns the last selected items so it won’t work where there are multiple items selected):

Multiple selections

If the ListBox has multiple selections and you want to get all the data from each then you can use the GetSelectedRows() sub from the section VBA ListBox Selected Items. This will get a collection of all selected rows. You can use this to print the data from the selected rows:

VBA ListBox MultiSelect

We can use the MultiSelect property of the ListBox to allow the user to select either a single item or multiple items:

There are 3 selections:

  • 0 = frmMultiSelectSingle – [Default]Multiple selection isn’t allowed.
  • 1 = frmMultiSelectMulti – Multiple items are selected or deselected by choosing them with the mouse or by pressing the Spacebar.
  • 2 = frmMultiSelectExtended – Multiple items are selected by holding down Shift and choosing them with the mouse, or by holding down Shift and pressing an arrow key to extend the selection from the previously selected item to the current item. You can also select items by dragging with the mouse. Holding down Ctrl and choosing an item selects or deselects that item.

VBA ListBox Columns

You can have multiple columns in a ListBox. For example, you can load a Range or two-dimensional array to a ListBox using List or RowSource.

Often when you load data with multiple columns only one column appears. This can be very confusing when you are using the Listbox. To get the columns to appear you have to set the ColumnCount property to the number of Columns.

You should also make sure that the ColumnWidths property is correct or one of the columns may not appear.

You can do it like this:

In a real-world application, you could set the RowSource and ColumnCount properties like this:

See the AddItem section for how to add data to the other columns when you are using the AddItem property.

VBA ListBox Column Headers

Column Headers are another confusing element of the ListBox. If you use the RowSource property to add data to the ListBox then the line above the Range will be automatically used as the header.

For the Column headers to appear the ColumnHeads property must be set to true. You can do this in the properties window of the ListBox or in the code list this:

If you use the List or AddItem property to fill the ListBox then the column headers are not available. The best solution, albeit a frustrating one, is to use labels above the ListBox. I know it sounds crazy but that unfortunately is the reality. The one advantage is that you can use the Label click event which is useful if you plan to sort the data by a column.

Creating a ListBox Dynamically

Controls are normally created at design time but you can also create them dynamically at run time:

If you want to add an event to a dynamic control you can do it like this:

    First of all create a Class like this:

Name the class clsListBoxEvents. Create a variable of this class object in the UserForm like this:

  • Attach the events to the ListBox:
  • Note that you can attach events to any ListBox. It doesn’t have to be created dynamically to do this.

    Loop through ListBoxes

    If you want to loop through all the ListBoxes on a UserForm you can do it like this:

    YouTube Video

    Check out this video where I use the ListBox. The source code for the video is available from here

    What’s Next?

    Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out this Free VBA Tutorial.

    Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

    (NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

    Professor Kelly,
    Thank you for your kind generosity and continuing willingness to share your wealth of knowledge in your latest addition to what has really become the Excel Macro University. Hope to always see you in the lab.

    Thanks Ed, Glad you like it.

    Thanks for the connecting the dot. Information is power please continue to connect it.

    Hi. I have a question about ListBox.
    I am trying to use :
    but when i use this “ListBox.AddItem” but i got error Object required
    Please help me…

    You have to use the name of the ListBox. If you haven’t changed it then it is probably ListBox1.

    Also ListBox1 is not supported only ListBox supported but I should declare because ListBox.MouseIcon for example not working

    ListBox is the type of variable. ListBox1 is the default name. You may have used a different name.
    Dim a As MSForms.ListBox
    Set a = [name of your listbox]

    I have created ListBox in my project then i wrote these codes
    Dim a as ListBox
    Set a = MyListBox
    But i got type mismatch error

    Dim a As MSForms.ListBox
    Set a = MyListBox

    i think you are missing proper identification of object.
    Please test with below statement.

    I want to use this but i don’t know which variable or lemenet to put the instead of the ” *”‘

    Dim a As ListBox
    Set a = *

    I’m using Office 2016 Excel VBA.
    I noticed two things.
    .RowSource = “CardInfo!A2:AQ5″did not work until I did the following
    .RowSource =”‘CardInfo’!A2:AQ5” – single quotes around the sheet name and
    .ColumnCount = 43 When I left out the column count it only showed me the first column.
    Any thoughts on why?

    I’ve not seen any solution to my issue. As simple s possible: Sheet2 has 31,000 rows of data. I am only interested in showing data in column C in Textbox1.
    Listbox1 Rowsource = =Sheet2!A2:D31103. and Textbox1 are on Userform2.
    This code only pastes the selected item in Listbox1 on the form into Textbox1.
    Private Sub ListBox1_Change()
    UserForm2.TextBox1 = UserForm2.ListBox1.List(UserForm2.ListBox1.ListIndex, 2)
    I want it to paste any group of multiselected items into Textbox1 APPENDED to the already pasted previous items in Textbox1. To me, for this to work, any single item or group of multiselected items needs to be copied and pasted in another Blank Sheet column. H. Column H then grows as data is pasted below the last row. For me, this is complicated. Can you help me with this ? Thanks, cr
    End Sub

    I’m having trouble implementing this as well. A couple questions…

    1) is this a MSForms or ActiveX ListBox? It appears to be a form control and I’ve implemented it as described by Paul in previous comments, but I don’t have the RowSource method available (List and AddItem are available).

    2) Is there a way to change the ListBox name to something more meaningful than ListBox1? It can be changed in the range definition in excel, but this isn’t reflected in VBA where I still need to set the reference as below as I see no way to access the control properties.

    What am I not getting here? I’m using office 365 if that’s an issue, or the other issue might be that I am trying to implement it directly to a worksheet rather than a userform.

    Public Sub SetupListBox()
    Dim LB_Metal As MSForms.ListBox
    Set LB_Metal = Sheet1.ListBox1
    Dim rList As Range
    Set rList = wsVBA.Range(“MAT1_MID”)
    With LB_Metal
    .RowSource = rList ‘ Error 438: Object doesn’t support this property or method
    .ColumnHeads = True
    End With
    End Sub

    1. Dim fruit As String
    fruit = ListBox1.Value

    2. Dim fruit As String
    fruit = ListBox1.Text

    Example 1 returned “”
    Example 2 returned “apple”

    Hello, I’m currently doing a VBA project, just wondering how can i delete a data in two listbox . provided that i can match a unique key identifier for both listboxes

    Hello, Thanks for such clear explanations. Hoping for some help.

    I have a listbox (sourced from a datasheet).

    When a record is selected, the background is ugly MS blue background, with white font. I’m assuming this is related to colourtheme or default as I’ve not coded anything related to the list box (other than it’s very basic elements).

    I”ve searched for code to do this, but all solutions are extremely convoluted. There must be an element that can be changed, as without any code by me, selected_list comes up blue.

    Hoping you can help.

    My this code is only taking column a2:a11 .
    Can you please help me to get this proper result ?

    ListBox1.RowSource = “sheet1!A2:D11”
    ListBox1.ColumnHeads = True

    Make sure to set the column number

    Primeramente, lo felicito por su labor y excelente sus explicaciones
    Tengo una pregunta:
    • ¿Cómo imprimir la lista que se encuentra en un ListBox?
    • ¿Cómo imprimir esa lista filtrada a través de un TextBoxde ListBox?
    Por la atención que le presta a la presente, quedaré muy agardecido.

    Very impressed with the Data entry form Paul, I have used it but have added a copy button so you can then copy a chosen row to the end of the list where you can then edit the new row, I run lots of Cisco scripts and use this to write to text files, a lot of the scripts are very much the same, so a copy and edit really helps.

    Источник

    The VBA ListBox is a very useful control. If you are creating any kind of UserForm application you will most likely use it.

    In this post, I’m going to show you everything you need to know about the VBA ListBox so you can avoid the common pitfalls and get up and running quickly and easily.

    VBA ListBox multi

    What is the VBA ListBox used for?

    The ListBox is used to display a list of items to the user so that the user can then select one or more. The ListBox can have multiple columns and so it is useful for tasks like displaying records.

    VBA ListBox versus the VBA ComboBox

    The ListBox is very similar to the ComboBox which also allows the user to select an item from a list of items. The main differences are:

    1. The Listbox allows multiple selections. The Combobox only allows one selection.
    2. Items in the ListBox are always visible. The Combobox items are only visible when you click on the “down” icon.
    3. The ComboBox has the ability to filter the contents when you type.

    The VBA ListBox Properties Quick Guide

    Function Operation Example
    AddItem Add an item listbox.AddItem «Spain»
    Clear Remove all Items listbox.Clear
    ColumnCount Set the number of visible columns ComboBox1.ColumnCount = 2
    ColumnHeads Make the column row visible ComboBox1.ColumnHeads = True
    List Range to Listbox
    ListBox to Range
    Listbox.List = Range(«A1:A4»).Value
    Range(«A1:A4»).Value = Listbox.List
    List Update a column value Listbox.List(1,2) = «New value»
    ListCount Get the number of items cnt = listbox.ListCount
    ListIndex Get/set selected item Idx = listbox.ListIndex
    combo.ListIndex = 0
    RemoveItem Remove an item listbox.Remove 1
    RowSource Add a range of values from a worksheet ComboBox1.RowSource = Sheet1.Range(«A2:B3»).Address
    Value Get the value of selected Item Dim sCountry As String
    sCountry = listbox.Value

    How to Add Items to the ListBox

    There are 3 ways to add items to the VBA Listbox:

    1. One at a time using the AddItem property.
    2. Adding an array/range using the List property.
    3. Adding a Range using the RowSource property.

    The List and RowSource properties are the most commonly used. The table below provides a quick comparison of these properties:

    Task RowSource List
    Column Headers Yes No
    Update values in ListBox No Yes
    Add new items No Yes
    Data type Range Array(including Range.Value)
    If source data changes Listbox is automatically updated. ListBox is not updated.

    VBA ListBox List Property

    The List property allows you to add to contents of an array to a ListBox. As Range.Value is an array you can copy the contents of any range to the Listbox.

    Here are some examples of using the List property:

    ' Add the contents of an array
    ListBox1.List = Array("Apple", "Orange", "Banana")
    
    ' Add the contents of a Range
    ListBox1.List = Range("A1:E5").Value
    

    You can also use the List property to write from the ListBox to an array or range:

    Range("A1:B3").Value = ListBox1.List
    

    Important Note: If there is only one item in a range then VBA doesn’t covert it to an array. Instead, it converts the range to a string/double/date etc.

    Sheet1.Range("A1:A2").Value ' Array
    Sheet1.Range("A1").Value ' Single value variable
    

    In this case, you need to use AddItem to add the value to the ListBox:

     If myRange.Count = 1 Then
        ListBox1.AddItem myRange
     Else
        ListBox1.List = myRange.Value
     End If
    

    The List Property and Column Headers

    The ListBox only displays column headers if you use RowSource. Otherwise, they are not available. The best way to add column headers(and it’s not a great way) is to add Labels above the ListBox columns. One advantage is that you can use the click event of the Label if you want to implement something like sorting.

    Updating Items using the List Property

    You can update individual items in the ListBox using the List Property.

    Imagine we have a ListBox with data like this:

    If we want to change Nelson in row 3, column 2 we do it like this:

    ListBox1.List(2, 1) = "SMITH"
    

    The result we get is:

    The List property rows and columns are zero-based so this means row 1 is 0, row 2 is 1, row 3 is 2 and so on:

    VBA ListBox RowSource

    The RowSource property allows us to add a range to the ListBox. This is different from the List Property in that the Range is linked to the ListBox. If data in the Range changes then the data in the ListBox will update automatically.

    When we use RowSource the data in the ListBox is read-only. We can change the RowSource range but we cannot change the values in the ListBox.

    How to use RowSource

    We add the RowSource range as a string like this:

     ListBox1.RowSource = "Sheet1!A1:A5"
    

    If you don’t specify the sheet the VBA will use the active sheet

     ListBox1.RowSource = "A1:A5"
    

    If you are using the Address of a range object with RowSource then it is important to use the External parameter. This will ensure that RowSource will read from the  sheet of the range rather than the active sheet:

     ' Get the range
     Dim rg As Range
     Set rg = Sheet1.Range("A1:A5")
    
     ' Address will be $A$1:$A$5 which will use the active sheet
     ListBox1.RowSource = rg.Address
     Debug.Print ListBox1.RowSource
    
     ' Address will be [Book2]Sheet1!$A$1:$A$5 which will use Sheet1
     ListBox1.RowSource = rg.Address(External:=True)
     Debug.Print ListBox1.RowSource
    

    RowSource Column Headers

    Column headers are automatically added to the ListBox when you use the RowSource property. The ColumnHeads property must be set to True or the headers will not appear. You can set this property in the code or in the properties window of the ListBox.

      ListBox1.ColumnHeads = True

    The column headers are taken from the row above the range used for the RowSource.  For example, if your range is A2 to C5 then the column header will use the range A1 to C1:

    Here is an example: We want to add the data below to our ListBox and we want A1 to C1 to be the header.

    We set the RowSource property to A2:C5 and set the ColumnHeads property to true:

    With ListBox1
        .RowSource = "sheet1!A2:C5"
        .ColumnHeads = True
        .ColumnWidths = "80;80;80"
    End With
    

    The result will look like this:

    VBA ListBox AddItem

    It is very rare that you would use the AddItem property to fill the ListBox. List and RowSource are much more efficient. AddItem is normally used when the Listbox already has items and you want to add a new item.

    The AddItem property is simple to use. You provide the item you want to add as a parameter. The ListBox will automatically add it as the last item:

    With ListBox
        .AddItem "Apple"
        .AddItem "Orange"
    End With
    

    If you want to Insert the item at a certain position you can use the second parameter. Keep in mind that this is a zero-based position, so if you want the item in position one then the value is 0, position 2 the value is 1, and so on.

    With ListBox1
        .AddItem "Apple"
        .AddItem "Orange"
        
        ' Add "Banana" to position 1(Index 0)
        .AddItem "Banana", 0
    End With
    

    The order will be:
    Banana
    Apple
    Orange

    If you want to add multiple columns with AddItem then you need to use the List property after you use AddItem:

     With listboxFruit
        .List = myRange.Value
        .AddItem "Banana"
        
        ' Add to the second column of 'Banana' row
        .List(2, 1) = "$2.99"
     End With
    

    One reason for using AddItem  is if you are adding from data that isn’t sequential so you cannot use the List or RowSource properties:

     Dim cell As Range
     ' Fill items with first letter is A
     For Each cell In Sheet1.Range("A1:A50")
        If Left(cell.Value, 1) = "A" Then
            comboBoxFruit.AddItem cell.Value
        End If
     Next
    

    Important Note: If you fill a ListBox with RowSource then you cannot use AddItem to add a new item. If you try you will get a “Runtime Error 70 – Permission Denied”.

    VBA ListBox Selected Items

    If only one item is selected then you can use ListIndex to get the selected row. Remember that it is zero-based so row 1 in the ListBox is at ListIndex 0, row 2 at ListIndex 1 and so on.

       MsgBox "The selected item is " & ListBox1.ListIndex
    

    If the ListBox has multiple columns then you can use the ListIndex and List properties together to return a value in the selected row:

      ' Display the value from the second column of the selected row
      MsgBox ListBox1.List(ListBox1.ListIndex, 2)
    

    If multiple items are selected then you can use the GetSelectedRows function which returns a collection of selected rows:

     Sub Example()
        
        ' Store the row numbers of selected items to a collection
        Dim selectedRows As Collection
        Set selectedRows = GetSelectedRows()
        
        ' Print the selected rows numbers to the Immediate Window
        Dim row As Long
        For Each row In selectedRows
            ' Print to the Immediate Window Ctrl + G
            Debug.Print row
        Next row
    
     End Sub
    
     ' Returns a collection of all the selected items
     Function GetSelectedRows() As Collection
    
        ' Create the collection
        Dim coll As New Collection
    
        ' Read through each item in the listbox
        Dim i As Long
        For i = 0 To listboxFruit.ListCount - 1
        
            ' Check if item at position i is selected
            If listboxFruit.Selected(i) Then
                coll.Add i
            End If
        Next i
    
        Set GetSelectedRows = coll
    
    End Function
    

    Reading Data from the VBA Listbox

    To read data from the ListBox we can use the ListBox.Value property. This only works when the ListBox is set to only select one item i.e. MultiSelect is set to frmMultiSelectSingle(see the section VBA ListBox MultiSelect below for more about this).

    Single selection only  with one column

    When only one item is selected we can use the Value property to get the currently selected item:

     Dim fruit As String
     fruit = ListBox1.Value
    

    Keep in mind that if there are multiple columns, Value will only return the value in the first column.

    Single selection only with multiple columns

    If the ListBox has Multiple columns you can use the Value property to get the value in the first column. You need to read through the List property to get the values in the other column(s). The List property is essentially an array so you can treat it like one.

    In the example below we read through the columns of row 1(the index of row 1 is 0):

     With ListBox1
     
         For j = LBound(.List, 2) To UBound(.List, 2)
             ' Print the columns of the first row to the Immediate Window
             Debug.Print .List(0, j)
         Next j
         
     End With
    

    Normally you want to print the values in the selected row. You can use the ListIndex property to get the selected item(Note that ListIndex returns the last selected items so it won’t work where there are multiple items selected):

     ' ExcelMacroMastery.com
     Sub ReadValuesFromSelectedRow()
    
        ' Write contents of the row to the Immediate Window(Ctrl G)
        With ListBox1 
            For j = LBound(.List, 2) To UBound(.List, 2) 
                ' Print the columns of the selected row to the Immediate Window 
                Debug.Print .List(.ListIndex, j) Next j 
        End With
     End Sub
     
    

    Multiple selections

    If the ListBox has multiple selections and you want to get all the data from each then you can use the GetSelectedRows() sub from the section VBA ListBox Selected Items. This will get a collection of all selected rows. You can use this to print the data from the selected rows:

    Sub PrintMultiSelectedRows()
    
        ' Get all the selected rows
        Dim selectedRows As Collection
        Set selectedRows = GetSelectedRows(Me.ListBox1)
    
        Dim i As Long, j As Long, currentRow As Long
        ' Read through the selected rows
        For i = 1 To selectedRows.Count
            With ListBox1
                
                ' Get the current row
                currentRow = selectedRows(i)
                
                ' Print row header
                Debug.Print vbNewLine & "Row : " & currentRow
                
                ' Read items in the current row
                For j = LBound(.List, 2) To UBound(ListBox1.List, 2)
                    ' Print the columns of the first row to the Immediate Window
                    Debug.Print .List(currentRow, j)
                Next j
            
            End With
        Next i
        
    End Sub
    
    Function GetSelectedRows(currentListbox As MSForms.ListBox) As Collection
    
        ' Create the collection
        Dim coll As New Collection
    
        ' Read through each item in the listbox
        Dim i As Long
        For i = 0 To currentListbox.ListCount - 1
        
            ' Check if item at position i is selected
            If currentListbox.Selected(i) Then
                coll.Add i
            End If
        Next i
    
        Set GetSelectedRows = coll
    
    End Function
    

    VBA ListBox MultiSelect

    We can use the MultiSelect property of the ListBox to allow the user to select either a single item or multiple items:

    listbox multiselect

    There are 3 selections:

    • 0 = frmMultiSelectSingle –  [Default]Multiple selection isn’t allowed.
    • 1 = frmMultiSelectMulti – Multiple items are selected or deselected by choosing them with the mouse or by pressing the Spacebar.
    • 2 = frmMultiSelectExtended – Multiple items are selected by holding down Shift and choosing them with the mouse, or by holding down Shift and pressing an arrow key to extend the selection from the previously selected item to the current item. You can also select items by dragging with the mouse. Holding down Ctrl and choosing an item selects or deselects that item.

    VBA ListBox Columns

    You can have multiple columns in a ListBox. For example, you can load a Range or two-dimensional array to a ListBox using List or RowSource.

    Often when you load data with multiple columns only one column appears. This can be very confusing when you are using the Listbox. To get the columns to appear you have to set the ColumnCount property to the number of Columns.

    You should also make sure that the ColumnWidths property is correct or one of the columns may not appear.

    You can do it like this:

    With listboxFruit
        .RowSource = "Sheet1!A2:B4"
        .ColumnCount = 2
        .ColumnWidths = "100,100"
    End With
    

    In a real-world application, you could set the RowSource and ColumnCount properties like this:

    With listboxFruit
        .RowSource = myRange.Address(External:=True)
        .ColumnCount = myRange.Columns.Count
    End With
    

    See the AddItem section for how to add data to the other columns when you are using the AddItem property.

    VBA ListBox Column Headers

    Column Headers are another confusing element of the ListBox. If you use the RowSource property to add data to the ListBox then the line above the Range will be automatically used as the header.

    For the Column headers to appear the ColumnHeads property must be set to true. You can do this in the properties window of the ListBox or in the code list this:

    ListBox1.ColumnHeads = True
    

    If you use the List or AddItem property to fill the ListBox then the column headers are not available. The best solution, albeit a frustrating one, is to use labels above the ListBox. I know it sounds crazy but that unfortunately is the reality. The one advantage is that you can use the Label click event which is useful if you plan to sort the data by a column.

    Creating a ListBox Dynamically

    Controls are normally created at design time but you can also create them dynamically at run time:

        Dim myListbox As MSForms.ListBox
        Set myListbox = Controls.Add("Forms.ListBox.1")
    

    If you want to add an event to a dynamic control you can do it like this:

    1. First of all create a Class like this:
      Public WithEvents myListBox As MSForms.ListBox
      
      Private Sub myListBox_Change()
        MsgBox "Selection changed"
      End Sub
      
    2. Name the class clsListBoxEvents.  Create a variable of this class object in the UserForm like this:
      Private listBoxEvents As New clsListBoxEvents
      
    3.   Attach the events to the ListBox:
      Sub CreateDynamicListBox()
      
          ' Create the ListBox
          Dim newListBox As MSForms.ListBox
          Set newListBox = Controls.Add("Forms.ListBox.1")
          
          ' Add some items
          newListBox.List = Array("Apple", "Orange", "Pear")
         
          ' Connect the ListBox to the ListBox events class
          Set listBoxEvents.myListBox = newListBox
      
      End Sub
      

    Note that you can attach events to any ListBox. It doesn’t have to be created dynamically to do this.

    Loop through ListBoxes

    If you want to loop through all the ListBoxes on a UserForm you can do it like this:

     Dim ctrl As Variant
     For Each ctrl In Me.Controls
        If TypeName(ctrl) = "ListBox" Then
            Debug.Print ctrl.Name
        End If
     Next ctrl
    

    YouTube Video

    Check out this video where I use the ListBox. The source code for the video is available from here

     

    What’s Next?

    Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out this Free VBA Tutorial.

    Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

    (NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

    In This Chapter

    Understanding each type of dialog box control Changing each control’s properties Working with dialog box controls user responds to a custom dialog box (also known as a UserForm) by using the various controls (buttons, edit boxes, option buttons, and so on) that the dialog box contains. Your VBA code then makes use of these responses to determine which actions to take. You have lots of controls at your disposal, and this chapter tells you about them.
    If you worked through the hands-on example in Chapter 16, you already have some experience with UserForm controls. This chapter fills in the gaps.

    Getting Started with Dialog Box Controls

    In this section, I tell you how to add controls to a UserForm, give them meaningful names, and adjust some of their properties.
    Before you can do any of these things, you must have a UserForm, which you get by choosing InsertOUserForm in the VBE. When you add a UserForm, make sure that the correct project is selected in the Project window (if more than one project is available).

    Adding controls

    Oddly enough, the VBE doesn’t have menu commands that let you add controls to a dialog box. You must use the Toolbox, which I describe in the preceding chapter, to add controls. Normally, the Toolbox pops up automatically when you activate a UserForm in the VBE. If it doesn’t, you can display the Toolbox by choosing ViewOToolbox.

    Follow along to add a control to the UserForm:

    1. Click the Toolbox tool that corresponds to the control you want to add.
    2. Click in the UserForm.
    3. Drag the control into position.
    Alternatively, you can simply drag a control from the Toolbox to the UserForm to create a control with the default dimensions. Figure 17-1 shows a UserForm that contains a few controls.
    A UserForm with a few controls added.
    Figure 17-1:
    A UserForm with a few controls added.
    A UserForm may contain vertical and horizontal grid lines, which help align the controls you add. When you add or move a control, it snaps to the grid. If you don’t like this feature, you can turn off the grids:
    1. Choose ToolsOOptions in the VBE.
    2. In the Options dialog box, select the General tab.
    3. Set your desired options in the Form Grid Settings section.

    Introducing control properties

    Every control that you add to a UserForm has properties that determine how the control looks and behaves. You can change a control’s properties at these two times:
    At design time — when you’re designing the UserForm. You do so manually, using the Properties window.
    At run time — while your program is running. You do so by writing VBA code.
    When you add a control to a UserForm, you almost always need to make some design-time adjustments to its properties. You make these changes in the
    Properties window. (To display the Properties window, press F4.) Figure 17-2 shows the Properties window, which displays properties for the object selected in the UserForm.
    Use the Properties window to make design-time changes to a control's properties.
    Figure 17-2:
    Use the Properties window to make design-time changes to a control’s properties.
    To change a control’s properties at run time you must write VBA code. For example, you may want to hide a particular control when a check box is checked by the user. In such a case, you would write code to change the control’s Visible property.
    Each control has its own set of properties. All controls, however, share some common properties, such as Name, Width, and Value. Table 17-1 lists some of the common properties available for most controls.

    Table 17-1 Common Control Properties
    Property What It Does
    Accelerator The letter underlined in the control’s caption. The user
    presses this key in conjunction with the Alt key to select
    the control.
    AutoSize If True, the control resizes itself automatically based on
    the text in its caption.
    BackColor The control’s background color.
    BackStyle The background style (transparent or opaque).
    Caption The text that appears on the control.
    Value The control’s value.
    Table 17-1 (continued)
    Property What It Does
    Left and Top Values that determine the control’s position.
    Width and Height Values that determine the control’s width and height.
    Visible If False, the control is hidden.
    Name The control’s name. By default, a control’s name is based
    on the control type. You can change the name to any valid
    name, but each control’s name must be unique within the
    dialog box.
    Picture A graphics image to display. The image must be contained
    in a file; it can’t be copied from the Clipboard.

    When you select a control, that control’s properties appear in the Properties window. To change a property, just select it in the Properties window and make the change. Some properties give you some help. For example, if you need to change the TextAlign property, the Properties window displays a drop-down list that contains all valid property values as shown in Figure 17-3.
    Change properties by selecting from a dropdown list of valid property values.
    Figure 17-3:
    Change properties by selecting from a dropdown list of valid property values.

    Dialog Box Controls — the Details

    In the following sections I introduce you to each type of control you can use in custom dialog boxes and discuss some of the more useful properties. I don’t discuss every property for every control because that would take up too much space (and would be very boring).
    The Help system for controls and properties is thorough. To find complete details for a particular property, select the property in the Properties window and press Fl. Figure 17-4 shows part of the online help for the ControlSource property.
    The Help system provides lots of information for each property and control.
    Figure 17-4:
    The Help system provides lots of information for each property and control.
    All of the sample files in this section are available at this topic’s Web site.

    CheckBox control

    A CheckBox control is useful for getting a binary choice: yes or no, true or false, on or off, and so on. Figure 17-5 shows some examples of CheckBox controls.
    CheckBox controls.
    Figure 17-5:
    CheckBox controls.

    The following is a description of a CheckBox control’s most useful properties:

    Accelerator: A letter that lets the user change the value of the control by using the keyboard. For example, if the accelerator is A, pressing Alt+A changes the value of the CheckBox control (from checked to unchecked, or from unchecked to checked).
    ControlSource: The address of a worksheet cell that’s linked to the CheckBox. The cell displays TRUE if the control is checked or FALSE if the control is not checked.
    Value: If True, the CheckBox has a checkmark. If False, it does not have a checkmark.

    ComboBox control

    A ComboBox control is similar to a ListBox control (described later, in this chapter’s “ListBox control” section). A ComboBox, however, is a drop-down box and displays only one item at a time. Another difference is that the user may be allowed to enter a value that does not appear in the list of items. Figure 17-6 shows two ComboBox controls.
    ComboBox controls.
    Figure 17-6:
    ComboBox controls.

    The following is a description of some useful ComboBox control properties:

    BoundColumn: If the list contains multiple columns, this property determines which column contains the returned value.
    ColumnCount: The number of columns in the list.
    ControlSource: A cell that stores the value selected in the ComboBox.
    ListRows: The number of items to display when the list drops down.
    ListStyle: The appearance of the list items.
    RowSource: A range address that contains the list of items displayed in the ComboBox.
    Style: Determines whether the control acts like a drop-down list or a combo box. A drop-down list doesn’t allow the user to enter a new value.
    Value: The text of the item selected by the user and displayed in the ComboBox.
    If your list of items is not in a worksheet, you can add items to a ComboBox control by using the AddItem method. More information on this method is provided in Chapter 18.

    CommandButton control

    CommandButton is simply a clickable button. It is of no use unless you provide an event-handler procedure to execute when the button is clicked. Figure 17-7 shows a dialog box with a few CommandButtons. One of these buttons features a picture (specified using the Picture property).
    Command Button controls.
    Figure 17-7:
    Command Button controls.
    When a CommandButton is clicked, it executes a macro with a name that consists of the CommandButton’s name, an underscore, and the word Click. For example, if a command button is named MyButton, clicking it executes the macro named MyButton_Click. This macro is stored in the Code window for the UserForm.

    The following is a description of some useful CommandButton control properties:

    Cancel: If True, pressing Esc executes the macro attached to the button. ‘ Default: If True, pressing Enter executes the macro attached to the button.

    Frame control

    A Frame control encloses other controls. You do so either for aesthetic purposes or to logically group a set of controls. A frame is particularly useful when the dialog box contains more than one set of OptionButton controls. (See “OptionButton control,” later in this chapter.)

    The following list describes some useful Frame control properties:

    BorderStyle: The frame’s appearance.
    Caption: The text displayed at the top of the frame. The caption can be an empty string if you don’t want the control to display a caption.

    Image control

    An Image control displays an image. You may want to use an Image control to display your company’s logo in a dialog box. Figure 17-8 shows a dialog box with an Image control that displays a photo of a famous Excel topic author.

    The following list describes the most useful Image control properties:

    Picture: The graphics image that is displayed.
    PictureSizeMode: How the picture is displayed if the control size does not match the image size.
    When you click the Picture property, you are prompted for a filename. However, the graphics image is stored in the workbook. That way, if you distribute your workbook to someone else, you don’t have to include a copy of the graphics file.
    Here’s an easy way to set the Picture property: Copy the image to the Clipboard, select the Image property in the Properties box, and press Ctrl+V to paste the copied image.
    Some graphics images are very large and can make your workbook size increase dramatically. For best results, use an image that’s as small as possible.

    Label control

    A Label control simply displays text in your dialog box. Figure 17-9 shows a few Label controls. As you can see, you have a great deal of influence over the formatting of a Label control.
    Label controls are easily molded.
    Figure 17-9:
    Label controls are easily molded.

    ListBox control

    The ListBox control presents a list of items from which the user can choose one or more. Figure 17-10 shows a dialog box with two ListBox controls.
    ListBox controls.
    Figure 17-10:
    ListBox controls.
    ListBox controls are very flexible. For example, you can specify a worksheet range that holds the ListBox items, and the range can consist of multiple columns. Or you can fill the ListBox with items by using VBA code.

    The following is a description of the most useful ListBox control properties:

    BoundColumn: If the list contains multiple columns, this property determines which column contains the returned value.
    ColumnCount: The number of columns in the list.
    ControlSource: A cell that stores the value selected in the ListBox.
    IntegralHeight: This is True if the ListBox height adjusts automatically to display full lines of text when the list is scrolled vertically. If False, the ListBox may display partial lines of text when it is scrolled vertically.
    ListStyle: The appearance of the list items.
    MultiSelect: Determines whether the user can select multiple items from
    the list.
    RowSource: A range address that contains the list of items displayed in the ListBox.
    Value: The text of the selected item in the ListBox.
    If the ListBox has its MultiSelect property set to 1 or 2, then the user can select multiple items in the ListBox. In such a case, you cannot specify a ControlSource; you need to write a macro that determines which items are selected. Chapter 18 demonstrates how to do so.

    MultiPage control

    A MultiPage control lets you create tabbed dialog boxes, like the one that appears when you choose the ToolsOOptions command. Figure 17-11 shows an example of a custom dialog box that uses a MultiPage control. This particular control has three pages, or tabs.
    Use a MultiPage control to create a tabbed dialog box.
    Figure 17-11:
    Use a MultiPage control to create a tabbed dialog box.

    Descriptions of the most useful MultiPage control properties follow:

    Style: Determines the appearance of the control. The tabs can appear normally (on the top), on the left, as buttons, or hidden (no tabs — your VBA code determines which page is displayed).
    Value: Determines which page or tab is displayed. A Value of 0 displays the first page, a Value of 1 displays the second page, and so on.
    By default, a MultiPage control has two pages. To add pages, right-click a tab and select New Page from the resulting Context menu.

    OptionButton control

    OptionButtons are useful when the user needs to select from a small number of items. OptionButtons are always used in groups of at least two. Figure 17-12 shows two sets of OptionButtons (Report Destination and Layout). One set uses graphics images (set with the Picture property).
    Two sets of Option Button controls, each contained in a Frame control.
    Figure 17-12:
    Two sets of Option Button controls, each contained in a Frame control.

    The following is a description of the most useful OptionButton control properties:

    Accelerator: A letter that lets the user select the option by using the keyboard. For example, if the accelerator for an option button is C, then pressing Alt+C selects the control.
    GroupName: A name that identifies an option button as being associated with other option buttons with the same GroupName property.
    ControlSource: The worksheet cell that’s linked to the option button. The cell displays TRUE if the control is selected or FALSE if the control is not selected.
    Value: If True, the OptionButton is selected. If False, the OptionButton is not selected.
    If your dialog box contains more than one set of OptionButtons, you must change the GroupName property for all OptionButtons in a particular set. Otherwise, all OptionButtons become part of the same set. Alternatively, you can enclose each set of OptionButtons in a Frame control, which automatically groups the OptionButtons in the frame.

    RefEdit control

    The RefEdit control is used when you need to let the user select a range in a worksheet. Figure 17-13 shows a custom dialog box with two RefEdit controls. Its Value property holds the address of the selected range.
    Two RefEdit controls.
    Figure 17-13:
    Two RefEdit controls.

    ScrollBar control

    The ScrollBar control is similar to a SpinButton control (described later). The difference is that the user can drag the ScrollBar’s button to change the control’s value in larger increments. Figure 17-14 shows a ScrollBar control. Its Value is displayed in a Label control.
    A ScrollBar control, with a Label control below it.
    Figure 17-14:
    A ScrollBar control, with a Label control below it.

    The following is a description of the most useful properties of a ScrollBar control:

    Value: The control’s current value. Min: The control’s minimum value. Max: The control’s maximum value.
    ControlSource: The worksheet cell that displays the control’s value.
    SmallChange: The amount that the control’s value is changed by a click.
    LargeChange: The amount that the control’s value is changed by clicking either side of the button.
    The ScrollBar control is most useful for specifying a value that extends across a wide range of possible values.

    SpinButton control

    The SpinButton control lets the user select a value by clicking the control, which has two arrows (one to increase the value and the other to decrease the value). Figure 17-15 shows a dialog box that uses two SpinButton controls. Each control is linked to the Label control on the right (by using VBA procedures).
    SpinButton controls.
    Figure 17-15:
    SpinButton controls.

    The following descriptions explain the most useful properties of a SpinButton control:

    Value: The control’s current value. Min: The control’s minimum value. Max: The control’s maximum value.
    ControlSource: The worksheet cell that displays the control’s value.
    SmallChange: The amount that the control’s value is changed by a click. Usually this property is set to 1, but you can make it any value.
    If you use a ControlSource for a SpinButton, you should understand that the worksheet is recalculated every time the control’s value is changed. Therefore, if the user changes the value from 0 to 12, the worksheet is calculated 12 times. If your worksheet takes a long time to calculate, you may want to avoid using a ControlSource to store the value.

    TabStrip control

    A TabStrip control is similar to a MultiPage control, but it’s not as easy to use. In fact, I’m not sure why this control is even included. You can pretty much ignore it and use the MultiPage control instead.

    TextBox control

    A TextBox control lets the user enter text. Figure 17-16 shows a dialog box with two TextBox controls.
    TextBox controls.
    Figure 17-16:
    TextBox controls.

    The following is a description of the most useful TextBox control properties:

    AutoSize: If True, the control adjusts its size automatically, depending on the amount of text.
    ControlSource: The address of a cell that contains the text in the TextBox.
    IntegralHeight: If True, the TextBox height adjusts automatically to display full lines of text when the list is scrolled vertically. If False, the TextBox may display partial lines of text when it is scrolled vertically.
    MaxLength: The maximum number of characters allowed in the TextBox. If 0, the number of characters is unlimited.
    MultiLine: If True, the TextBox can display more than one line of text.
    TextAlign: Determines how the text is aligned in the TextBox.
    WordWrap: Determines whether the control allows word wrap.
    ScrollBars: Determines the type of scroll bars for the control: horizontal, vertical, both, or none.

    ToggleButton control

    A ToggleButton control has two states: on and off. Clicking the button toggles between these two states, and the button changes its appearance when clicked. Its value is either True (pressed) or False (not pressed). You can sometimes use a toggle button in place of a CheckBox control. Figure 17-17 shows a dialog box with some ToggleButton controls.
    Toggle Button controls.
    Figure 17-17:
    Toggle Button controls.

    Working with Dialog Box Controls

    In this section, I discuss how to work with dialog box controls in a UserForm object.

    Moving and resizing controls

    After you place a control in a dialog box, you can move it and resize it by using standard mouse techniques. Or for precise control, you can use the Properties window to enter a value for the control’s Height, Width, Left, or Top property.
    You can select multiple controls by Ctrl+clicking the controls. Or you can click and drag to “lasso” a group of controls. When multiple controls are selected, the Properties window displays only the properties common to all selected controls.
    A control can hide another control; in other words, you can stack one control on top of another. Unless you have a good reason for doing so, make sure that you do not overlap controls.

    Aligning and spacing controls

    The Format menu in the VBE window provides several commands to help you precisely align and space the controls in a dialog box. Before you use these commands, select the controls you want to work with. These commands work just as you would expect, so I don’t explain them here. Figure 17-18 shows a dialog box with several CheckBox controls about to be aligned.
    Use the Formato Align command to change the alignment of UserForm controls.
    Figure 17-18:
    Use the Formato Align command to change the alignment of UserForm controls.
    When you select multiple controls, the last selected control appears with white handles rather than the normal black handles. The control with the white handles is the basis for aligning or resizing the other selected controls when you use the Format menu.

    Accommodating keyboard users

    Many users (including me) prefer to navigate through a dialog box by using the keyboard: Pressing Tab and Shift+Tab cycles through the controls, while pressing a hot key instantly activates a particular control.
    To make sure that your dialog box works properly for keyboard users, you must be mindful of two issues:
    Tab order Accelerator keys

    Changing the tab order

    The tab order determines the order in which the controls are activated when the user presses Tab or Shift+Tab. It also determines which control has the initial focus — that is, which control is the active control when the dialog box first appears. For example, if a user is entering text into a TextBox, the TextBox has the focus. If the user clicks an OptionButton, the OptionButton has the focus. The first control in the tab order has the focus when Excel first displays a dialog box.
    To set the control tab order, choose View Tab Order. You can also right-click the dialog box and choose Tab Order from the shortcut menu. In either case, Excel displays the Tab Order dialog box shown in Figure 17-19.
    The Tab Order dialog box.
    Figure 17-19:
    The Tab Order dialog box.
    The Tab Order dialog box lists all the controls in the UserForm. The tab order in the UserForm corresponds to the order of the items in the list. To move a control, select it and then click the arrow buttons up or down. You can choose more than one control (click while pressing Shift or Ctrl) and move them all at one time.
    Rather than use the Tab Order dialog box, you can set a control’s position in the tab order by using the Properties window. The first control in the tab order has a TabIndex property of 0. If you want to remove a control from the tab order, set its TabStop property to False.
    Some controls (such as Frame or MultiPage controls) act as containers for other controls. The controls inside a container control have their own tab order. To set the tab order for a group of OptionButtons inside a Frame control, select the Frame control before you choose the ViewOTab Order command.

    Setting hot keys

    Normally, you want to assign an accelerator key, or hot key, to dialog box controls. You do so by entering a letter for the Accelerator property in the Properties window. If a control doesn’t have an Accelerator property (a TextBox, for example), you can still allow direct keyboard access to it by using a Label control. That is, assign an accelerator key to the Label and put the Label directly before the TextBox in the tab order.
    Figure 17-20 shows several TextBoxes. The Labels that describe the TextBoxes have accelerator keys, and each Label precedes its corresponding TextBox in the tab order. Pressing Alt+D, for example, activates the TextBox next to the Department Label.
    Use Labels to provide direct access to controls that don't have accelerator keys.
    Figure 17-20:
    Use Labels to provide direct access to controls that don’t have accelerator keys.

    Testing a UserForm

    The VBE offers three ways to test a UserForm without calling it from a VBA procedure:
    Choose the RunORun Sub/UserForm command. Press F5.
    Click the Run Sub/UserForm button on the Standard toolbar.
    When a dialog box is displayed in this test mode, you can try out the tab order and the accelerator keys.

    Dialog Box Aesthetics

    Dialog boxes can look good, bad, or somewhere in between. A good-looking dialog box is easy on the eye, has nicely sized and aligned controls, and makes its function perfectly clear to the user. Bad-looking dialog boxes confuse the user, have misaligned controls, and give the impression that the developer didn’t have a plan (or a clue).
    A good rule to follow is to try to make your dialog boxes look like the Excel built-in dialog boxes. As you gain more experience with dialog box construction, you can duplicate almost all the features of the Excel dialog boxes.

    Like this post? Please share to your friends:
  • Excel vba for in list
  • Excel vba on error goto error
  • Excel vba listbox column
  • Excel vba for in array
  • Excel vba on change event cell