kare Пользователь Сообщений: 161 |
#1 11.07.2013 11:00:18 Доброе утро. Подскажите пожалуйста как посчитать количество заполненных строк в listbox1 ?
|
||
Fireman13 Пользователь Сообщений: 18 |
А данные беруться откуда или файл свой скиньте пожалуйста |
kare Пользователь Сообщений: 161 |
#3 11.07.2013 11:06:08 Fireman13, здравствуйте данные в листбоксе берутся по следующему алгоритму (отрытие кнниги с базой копирование значений загрузка в листбокс закрытие книги с базой) код загрузки листбокса :
Изменено: kare — 11.07.2013 11:06:58 |
||
Fireman13 Пользователь Сообщений: 18 |
А не легче забить список в этот же лист |
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Dim i as long Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
ListBox1.ListCount — не это искали? |
Fireman13 Пользователь Сообщений: 18 |
kare, кстати еще можно при выгрузке подсчитать их |
kare Пользователь Сообщений: 161 |
Fireman13, Изменено: kare — 11.07.2013 11:31:38 |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Fireman13, если уж без цитирования никак, то цитируйте хотя бы ТОЛЬКО нужное. |
kare Пользователь Сообщений: 161 |
Fireman13, |
Fireman13 Пользователь Сообщений: 18 |
#11 11.07.2013 11:24:20
Good |
||
Fireman13 Пользователь Сообщений: 18 |
kare, не могли вы мне скинуть пример файла |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
kare, так ListCount не подходит? И, как правильно заметил Дмитрий, тип переменной у Вас неверный. Или Вы хотите получить что-то другое? |
kare Пользователь Сообщений: 161 |
The_Prist, Юрий М, Спасибо . То что надо Изменено: kare — 11.07.2013 11:28:55 |
kare Пользователь Сообщений: 161 |
Fireman13, спасибо вопрос решен ! |
kare Пользователь Сообщений: 161 |
Юрий М, Раз мы заговорили об listbox. не подскажите от куда у меня постоянно остается 2 пустые срочки ?т.е. их можно выделять. но они не удаляются ((( |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Скорее всего они у Вас имеются в исходных данных — как можно сказать без файла… |
kare Пользователь Сообщений: 161 |
Юрий М, The_Prist, Изменено: kare — 11.07.2013 11:35:55 |
kare Пользователь Сообщений: 161 |
Юрий М, Изменено: kare — 11.07.2013 11:36:48 |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
Перебираем тогда циклом ячейки — если не пустая — в ЛистБокс. |
kare Пользователь Сообщений: 161 |
#21 11.07.2013 11:40:25 Юрий М,
Изменено: kare — 11.07.2013 11:40:36 |
||
kare Пользователь Сообщений: 161 |
#22 11.07.2013 11:45:17 Юрий М,
поставил на кнопку добавить , удалить ( но удалить добавил i-1) проблема решена. Изменено: kare — 11.07.2013 11:45:30 |
||
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#23 11.07.2013 11:51:50 Не так.
|
||
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#24 11.07.2013 12:02:35 Не обратил внимания, что у Вас несколько столбцов. Вот вариант для двух столбцов:
Вижу, что Hugo подглядывает : или сначала собрать в массив по условию, а затем Me.ListBox1.List=Массив |
||
Содержание
- ListBox.ListCount property (Access)
- Syntax
- Remarks
- Example
- Support and feedback
- Свойство ListBox.ListCount (Access)
- Синтаксис
- Замечания
- Пример
- Поддержка и обратная связь
- Thread: Solved: Listbox Selected Items Count?
- Solved: Listbox Selected Items Count?
- VBA Excel. Элемент управления ListBox (список)
- Элемент управления ListBox
- Свойства списка
- Способы заполнения ListBox
- VBA ListBox ColumnCount Property
- VBA Reference
- 120+ Project Management Templates
- ListBox_ColumnCount_Property – Syntax
- ListBox_ColumnCount_Property – Explanation & Example
- ListBox_ColumnCount_Property: Change Manually
- ListBox_ColumnCount_Property: Change Using Code
- Example Code 1:
- Example Code 2:
- Example Code 3:
ListBox.ListCount property (Access)
Use the ListCount property to determine the number of rows in a list box. Read/write Long.
Syntax
expression.ListCount
expression A variable that represents a ListBox object.
Microsoft Access sets the ListCount property to the number of rows in the list box or the list box portion of the combo box. The value of the ListCount property is read-only and can’t be set by the user.
This property is available only by using a macro or Visual Basic. You can read this property only in Form view and Datasheet view.
The ListCount property setting contains the total number of rows in the combo box list or list box, as determined by the control’s RowSource and RowSourceType properties. If the control is based on a table or query (the RowSourceType property is set to Table/Query and the RowSource property is set to a particular table or query), the ListCount property setting contains the number of records in the table or query result set. If the RowSourceType property is set to Value List, the ListCount property setting contains the number of rows that the value list specified in the RowSource property results in (this depends on the value list and the number of columns in the list box or combo box list, as set by the ColumnCount property).
If you set the ColumnHeads property to Yes, the row of column headings is included in the number of rows returned by the ListCount property. For combo boxes and list boxes based on a table or query, adding column headings adds an additional row. For combo boxes and list boxes based on a value list, adding column headings leaves the number of rows unchanged (the first row of values becomes the column headings).
Use the ListCount property with the ListRows property to specify how many rows you want to display in the list box portion of a combo box.
Example
The following example uses the ListCount property to find the number of rows in the list box portion of the CustomerList combo box on a Customers form. It then sets the ListRows property to display a specified number of rows in the list.
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.
Источник
Свойство ListBox.ListCount (Access)
Используйте свойство ListCount для определения количества строк в списке. Для чтения и записи, Long.
Синтаксис
expression. ListCount
Выражение Переменная, представляющая объект ListBox .
Замечания
Microsoft Access задает для свойства ListCount количество строк в списке или в поле со списком. Значение свойства ListCount доступно только для чтения и не может быть задано пользователем.
Это свойство доступно только с помощью макроса или Visual Basic. Это свойство можно прочитать только в режиме формы и в режиме таблицы.
Параметр свойства ListCount содержит общее количество строк в списке со списком или списке, которое определяется свойствами RowSource и RowSourceType элемента управления. Если элемент управления основан на таблице или запросе (для свойства RowSourceType задано значение Table/Query, а свойству RowSource задана определенная таблица или запрос), параметр свойства ListCount содержит количество записей в таблице или результирующем наборе запросов. Если свойство RowSourceType имеет значение Список значений, параметр свойства ListCount содержит количество строк, в которых приводит список значений, указанный в свойстве RowSource (это зависит от списка значений и количества столбцов в списке списка или списке со списком, заданное свойством ColumnCount ).
Если для свойства ColumnHeads задано значение Да, строка заголовков столбцов будет включена в число строк, возвращаемых свойством ListCount . Для полей со списком и списков, основанных на таблице или запросе, добавление заголовков столбцов добавляет дополнительную строку. Для полей со списком и списков, основанных на списке значений, добавление заголовков столбцов оставляет количество строк без изменений (первая строка значений становится заголовками столбцов).
Используйте свойство ListCount со свойством ListRows , чтобы указать, сколько строк нужно отобразить в поле со списком.
Пример
В следующем примере свойство ListCount используется для поиска количества строк в поле со списком CustomerList в форме Customers . Затем он задает свойство ListRows для отображения указанного количества строк в списке.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Thread: Solved: Listbox Selected Items Count?
Thread Tools
Display
Solved: Listbox Selected Items Count?
Hi.
Usually i use codes like this:
[vba]
Private Sub Cmd2_Click()
Dim item As Long, I As Long, msg As String
With ListBox1
For I = 0 To .ListCount — 1
If .Selected(I) Then
msg = msg & .List(I) & vbNewLine
End If
Next I
End With
If msg = vbNullString Then
MsgBox «Nothing was selected! Please make a selection!»
Exit Sub
Else
End If
End Sub
[/vba]
But in case if i need only value= selected.items?
How (is it possibe) put work function like this:
varSelectedItems = Listbox1.Selected.Items.Count
MsgBox varSelectedItems
[vba]Option Explicit
Private Sub ListBox1_Change()
Dim intIndex As Integer
Dim intCount As Integer
With ListBox1
For intIndex = 0 To .ListCount — 1
If .Selected(intIndex) Then intCount = intCount + 1
Next
End With
Label1.Caption = «Selected » & intCount & » out of » & ListBox1.ListCount
End Sub
Private Sub UserForm_Initialize()
With ListBox1
.AddItem «A»
.AddItem «B»
.AddItem «C»
.AddItem «D»
.AddItem «E»
.AddItem «F»
.AddItem «G»
End With
Label1.Caption = «None Selected»
End Sub[/vba]
Thanks Lucas.
Probably my quession was so abstruse.
I was thinking solusion like function.[vba]Sub USC()
Dim UsedCells As Long, x As Long
UsedCells = Application.WorksheetFunction.CountA(Range(«A:A»))
x = UsedCells
MsgBox x
End Sub
[/vba]
In my case function like:
SelectedItems = Appl.UFormFunction.CountSelectedItems(ListBox1)
[vba]
For i = 0 To (1 less than number of items)
If ListBox1.Selected(i) = True Then
NumSelections = NumSelections + 1
End If
Next i
Hi.
Probably function like: . Appl.UFormFunction.CountSelectedItems(ListBox1) impossible.
I solved this way.
Maybe not all correct but works.
Источник
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 для загрузки элементов в список по одному:
Источник
VBA ListBox ColumnCount Property
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
50+ Excel Templates
50+ PowerPoint Templates
25+ Word Templates
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
VBA ColumnCount Property of ListBox ActiveX Control in Excel specifies or represents the number of columns to be displayed in a listbox. We can set columncount value manually in the properties window. Or we can assign the value by using vba code.
ListBox_ColumnCount_Property – Syntax
Please find the below syntax of ListBox_ColumnCount_Property in Excel VBA.
ListboxName.ColumnCount=Number of Columns
Where ListboxName represents the ListBox object. In the above syntax we are using ‘ColumnCount’ property of ListBox object to set the number of columns in a listbox control.
ListBox_ColumnCount_Property – Explanation & Example
Here is the example for ListBox control ColumnCount_Property. It will take you through how to enable listbox control property of listbox using Excel VBA. Here you can find or see how we enable listbox using ‘ColumnCount’ property of listbox manually or using code.
ListBox_ColumnCount_Property: Change Manually
Please find the following details how we are changing manually ‘ColumnCount’ of listbox property.
-
- Go To Developer Tab and then click Visual Basic from the Code or Press Alt+F11.
- Go To Insert Menu, Click UserForm. Please find the screenshot for the same.
-
- Drag a Listbox on the Userform from the Toolbox.
-
- Right click on the List box. Click on properties from the available list.
-
- Now you can find the properties window of listbox on the screen. Please find the screenshot for the same.
-
- On the left side find ‘ColumnCount’ property from the available List Box properties.
- On the right side you can mention number. i.e an integer value.
- For example, I have entered 2. This means listbox contains two data columns. You can see the same in the screen shot for your understand.
ListBox_ColumnCount_Property: Change Using Code
Please find the following details how we are changing ColumnCount of listbox property with using Excel VBA code.
-
-
- Go To Developer Tab and then click Visual Basic from the Code or Press Alt+F11.
- Go To Insert Menu, Click UserForm. Please find the screenshot for the same.
-
-
-
- Drag a Listbox on the Userform from the Toolbox. Please find the screenshot for the same.
-
-
-
- Double Click on the UserForm, and select the Userform event as shown in the below screen shot.
-
-
-
- Now can see the following code in the module.
-
-
-
- Now, add the following example code1 or code2 or code3 to the in between above event procedure.
-
Example Code 1:
Here is the example and output when we set column count property to ‘-1’. This means it will display all columns in a listbox.
Output: If ColumnCount =-1
Please find the below output when we set ColumnCount property value is -1. It is shown in the following Screen Shot.
Example Code 2:
Here is the example and output when we set column count property to ‘0’. This means it will display no columns in a listbox.
Output: If ColumnCount =0
Please find the below output when we set ColumnCount property value is ‘0’. It is shown in the following Screen Shot.
Example Code 3:
Here is the example and output when we set column count property to 2. This means it will display two columns in a listbox.
Output: If ColumnCount =3
Please find the below output when we set ColumnCount property value is ‘3’. It is shown in the following Screen Shot.
Источник
-
#3
Last edited: Oct 24, 2016
-
#4
Try this:
Code:
Private Sub CommandButton13_Click()
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) = True Then
Numselections = Numselections + 1
End If
Next i
MsgBox Numselections
End Sub
-
#5
Try this:
Code:
Private Sub CommandButton13_Click() For i = 0 To ListBox1.ListCount - 1 If ListBox1.Selected(i) = True Then Numselections = Numselections + 1 End If Next i MsgBox Numselections End Sub
Thats what I needed! Thanks! Sorry about the duplicate posting
-
#6
Glad I was able to help you. Come back here to Mr. Excel next time you need additional assistance.
Thats what I needed! Thanks! Sorry about the duplicate posting
January 22, 2019/
Chris Newman
What Are ListBox Controls?
ListBoxes are a great way to manage tables within your userform. I have used them in the past to allow users to manage rows of information without necessary displaying all that information within the userform itself. There are a lot of neat things you can do with a userform so I’ve collected some of the more popular tasks you may want to know how to write within your VBA code.
For all the example VBA code snippets, the name of the listbox with be called “ListBox1”. I also have a downloadable example file that you can get for free if you want to see a lot of this code in action.
Enjoy!
Add An Item to The ListBox
To The End
To A Specific Position
Remember ListBoxes are zero based, so the first item is really at position 0. So if you want to add an item to the 5th position, you need to reference number 4 in the AddItem function.
‘Add to the 2nd Position (subtract 1 from desired)
ListBox1.AddItem «Apple», 1
Add Multiple Items To The ListBox
Individually Written
Sub ListBox_Load()
ListBox1.AddItem «Apple»
ListBox1.AddItem «Orange»
ListBox1.AddItem «Pear»
End Sub
From An Array List
Sub ListBox_LoadArray()
Dim myArray As Variant
myArray = Array(«Apple», «Orange», «Pear»)
ListBox1.List = myArray
End Sub
From A Cell Range
Sub ListBox_LoadRange()
Dim cell As Range
‘Load to ListBox
For Each cell In Worksheets(«Sheet1»).Range(«A1:A6»)
ListBox1.AddItem cell.Value
Next cell
End Sub
From A Table Object (ListObject)
Sub ListBox_LoadTable()
Dim tbl As ListObject
Dim cell As Range
‘Store Table Object to a variable
Set tbl = Sheet1.ListObjects(«Table1»)
‘Load List Box
For Each cell In tbl.DataBodyRange.Columns(1).Cells
ListBox1.AddItem cell.Value
Next cell
End Sub
Delete ListBox Items
Remove An Item From The ListBox
‘Remove 4th item in ListBox (subtract 1 from desired row)
ListBox1.RemoveItem 3
Remove Selected Item(s) From The ListBox
Private Sub DeleteSelection()
‘PURPOSE: Remove any selected items from the ListBox
Dim x As Long
Dim OriginalCount As Long
‘Store original ListBox count
OriginalCount = ListBox1.ListCount
‘Temporarily hide ListBox (runs faster)
ListBox1.Visible = False
‘Delete selected line items
For x = OriginalCount — 1 To 0 Step -1
If ListBox1.Selected(x) = True Then ListBox1.RemoveItem x
Next x
‘Unhide ListBox
ListBox1.Visible = True
End Sub
Remove All Items From The ListBox
Listbox Selected Items
Select A Specific Item In The ListBox
‘Select the 5th item in the ListBox (subtract 1 from desired row)
ListBox1.Selected(4) = True
Deselect All Items
Unfortunately, the “ListIndex = -1” method does not work when a ListBox allows for multiple selections. Hence, the below code tests for the ListBox’s selection mode.
If ListBox1.MultiSelect = fmMultiSelectSingle Then
ListBox1.ListIndex = -1
Else
For x = 0 To ListBox1.ListCount — 1
If ListBox1.Selected(x) Then ListBox1.Selected(x) = False
Next x
End If
Count How Many Items Are Selected (Function)
Function ListBoxSelectionCount(LB As ListBox) As Long
‘PURPOSE: Count how many items are selected in a give Listbox
Dim x As Long
Dim Count As Long
For x = 0 To LB.ListCount — 1
If LB.Selected(x) Then Count = Count + 1
Next x
ListBoxSelectionCount = Count
End Function
Count How Many Items Are In The ListBox
‘Return how many items are in the ListBox
MsgBox ListBox1.ListCount
Move Selected Item Up/Down
Move Selection Up One Position
Sub MoveUp()
‘PURPOSE: Move the selected item up one position in the list
Dim x As Long
Dim Count As Long
Dim Position As Long
‘Is there an item selected?
If ListBox1.ListIndex = -1 Then Exit Sub
‘Which Item is selected?
For x = 0 To ListBox1.ListCount — 1
If ListBox1.Selected(x) = True Then
Position = x
Count = Count + 1
If Count > 1 Then Exit Sub ‘More than 1 item selected
End If
Next x
‘Selected item already at the top?
If Position = 0 Then Exit Sub
‘Add an item above the current selection
ListBox1.AddItem ListBox1.List(Position), Position — 1
‘Remove Original Selection
ListBox1.RemoveItem Position + 1
‘Re-select the item that got moved
ListBox1.Selected(Position — 1) = True
End Sub
Move Selection Down One Position
Sub MoveDown()
‘PURPOSE: Move the selected item down one position in the list
Dim x As Long
Dim Count As Long
Dim Position As Long
‘Is A ValidSelection Made?
If ListBox1.ListIndex = -1 Then Exit Sub ‘No Selection made
‘Which Item is selected?
For x = 0 To ListBox1.ListCount — 1
If ListBox1.Selected(x) = True Then
Position = x
Count = Count + 1
If Count > 1 Then Exit Sub ‘More than 1 item selected
End If
Next x
‘Move selected item down if not already at the bottom
If Position < ListBox1.ListCount — 1 Then
‘Add an item below the current selection
ListBox1.AddItem ListBox1.List(Position), Position + 2
‘Remove Original Selection
ListBox1.RemoveItem Position
‘Re-select the item that got moved
ListBox1.Selected(Position + 1) = True
End If
End Sub
Additional Resources
-
Excel VBA UserForm Listbox (AnalysisTabs.com)
-
The Complete Guide to Excel VBA Form Control ListBoxes (wellsr.com)
Anything To Add?
I know there are a TON of things you can do with ListBoxes and if there are actions you are stuck trying to figure out, leave a comment below and I will try to add them to the guide. Please only ask for generic tasks and not super-specific ones. Also, if there is a more simplistic way to carry out some of these tasks, let me know!
Download The Excel Example File
If you would like to get a copy of the Excel file I used throughout this article, feel free to directly download the spreadsheet by clicking the download button below.
About The Author
Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.
Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!
— Chris
Founder, TheSpreadsheetGuru.com
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:
- The Listbox allows multiple selections. The Combobox only allows one selection.
- Items in the ListBox are always visible. The Combobox items are only visible when you click on the “down” icon.
- 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:
- One at a time using the AddItem property.
- Adding an array/range using the List property.
- 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:
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:
- First of all create a Class like this:
Public WithEvents myListBox As MSForms.ListBox Private Sub myListBox_Change() MsgBox "Selection changed" End Sub
- Name the class clsListBoxEvents. Create a variable of this class object in the UserForm like this:
Private listBoxEvents As New clsListBoxEvents
- 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.)