Excel vba listbox column

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.)

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

ListBox.Column property (Access)

vbaac10.chm11206

vbaac10.chm11206

access

Access.ListBox.Column

d393326a-4114-9ec2-fcfe-1ce74003e86c

02/28/2019

medium

ListBox.Column property (Access)

Use the Column property to refer to a specific column or column and row combination in a multiple-column combo box or list box. Read-only Variant.

Syntax

expression.Column (Index, Row)

expression A variable that represents a ListBox object.

Parameters

Name Required/Optional Data type Description
Index Required Long A long integer that can range from 0 to the setting of the ColumnCount property minus one.
Row Optional Variant An integer that can range from 0 to the setting of the ListCount property minus 1.

Remarks

Use 0 to refer to the first column, 1 to refer to the second column, and so on. Use 0 to refer to the first row, 1 to refer to the second row, and so on. For example, in a list box containing a column of customer IDs and a column of customer names, you could refer to the customer name in the second column and fifth row as:

 Forms!Contacts!Customers.Column(1, 4)

Use the Column property to assign the contents of a combo box or list box to another control, such as a text box. For example, to set the ControlSource property of a text box to the value in the second column of a list box, you could use the following expression.

 =Forms!Customers!CompanyName.Column(1)

If the user has made no selection when you refer to a column in a combo box or list box, the Column property setting will be Null. Use the IsNull function to determine if a selection has been made, as in the following example.

 If IsNull(Forms!Customers!Country) 
   Then MsgBox "No selection." 
 End If

[!NOTE]
To determine how many columns a combo box or list box has, you can inspect the ColumnCount property setting.

Example

The following example uses the Column property and the ColumnCount property to print the values of a list box selection.

Public Sub Read_ListBox() 
 
 Dim intNumColumns As Integer 
 Dim intI As Integer 
 Dim frmCust As Form 
 
 Set frmCust = Forms!frmCustomers 
 If frmCust!lstCustomerNames.ItemsSelected.Count > 0 Then 
 
 ' Any selection? 
 intNumColumns = frmCust!lstCustomerNames.ColumnCount 
 Debug.Print "The list box contains "; intNumColumns; _ 
 IIf(intNumColumns = 1, " column", " columns"); _ 
 " of data." 
 
 Debug.Print "The current selection contains:" 
 For intI = 0 To intNumColumns - 1 
 ' Print column data. 
 Debug.Print frmCust!lstCustomerNames.Column(intI) 
 Next intI 
 Else 
 Debug.Print "You haven't selected an entry in the " _ 
 & "list box." 
 End If 
 
 Set frmCust = Nothing 
 
End Sub

[!includeSupport and feedback]

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

Содержание

  1. Свойство ListBox.Column (Access)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Name already in use
  8. VBA-Docs / api / Access.ListBox.Column.md
  9. Things you can do with a multicolumn ListBox or ComboBox
  10. См. также
  11. Поддержка и обратная связь
  12. How to Set Column Header and Format Columns in VBA ListBox?
  13. 1 Answer 1
  14. VBA Excel Populate ListBox with multiple columns
  15. 2 Answers 2

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

Используйте свойство Column для ссылки на определенный столбец или сочетание столбцов и строк в поле со списком или списке с несколькими столбцами. Только для чтения, Variant.

Синтаксис

expression. Столбец (индекс, строка)

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

Параметры

Имя Обязательный или необязательный Тип данных Описание
Индекс; Обязательный Long Длинное целое число, которое может варьироваться от 0 до параметра свойства ColumnCount минус один.
Row Необязательный Variant Целое число, которое может варьироваться от 0 до параметра свойства ListCount минус 1.

Замечания

Используйте 0 для ссылки на первый столбец, 1 — на второй столбец и т. д. Используйте 0 для ссылки на первую строку, 1 — на вторую строку и т. д. Например, в списке со столбцом идентификаторов клиентов и столбцом имен клиентов можно сослаться на имя клиента во втором столбце и пятой строке следующим образом:

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

Если пользователь не сделал выбор при ссылке на столбец в поле со списком или списке, параметр свойства Column будет иметь значение NULL. Используйте функцию IsNull , чтобы определить, был ли сделан выбор, как показано в следующем примере.

Чтобы определить, сколько столбцов содержит поле со списком или список, можно проверить параметр свойства ColumnCount .

Пример

В следующем примере свойства Column и ColumnCount используются для печати значений выделенного списка.

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

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

Источник

Name already in use

VBA-Docs / api / Access.ListBox.Column.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

ListBox.Column property (Access)

Use the Column property to refer to a specific column or column and row combination in a multiple-column combo box or list box. Read-only Variant.

expression.Column (Index, Row)

expression A variable that represents a ListBox object.

Name Required/Optional Data type Description
Index Required Long A long integer that can range from 0 to the setting of the ColumnCount property minus one.
Row Optional Variant An integer that can range from 0 to the setting of the ListCount property minus 1.

Use 0 to refer to the first column, 1 to refer to the second column, and so on. Use 0 to refer to the first row, 1 to refer to the second row, and so on. For example, in a list box containing a column of customer IDs and a column of customer names, you could refer to the customer name in the second column and fifth row as:

Use the Column property to assign the contents of a combo box or list box to another control, such as a text box. For example, to set the ControlSource property of a text box to the value in the second column of a list box, you could use the following expression.

If the user has made no selection when you refer to a column in a combo box or list box, the Column property setting will be Null. Use the IsNull function to determine if a selection has been made, as in the following example.

[!NOTE] To determine how many columns a combo box or list box has, you can inspect the ColumnCount property setting.

The following example uses the Column property and the ColumnCount property to print the values of a list box selection.

Источник

Things you can do with a multicolumn ListBox or ComboBox

Чтобы управлять шириной столбцов многоколонок ListBox или ComboBox, можно указать ширину (в точках) для всех столбцов в свойстве ColumnWidths . Если для какого-нибудь конкретного столбца задать нулевую ширину, этот столбец станет скрытым и не будет отображаться на экране.

Если вы хотите скрыть от пользователя все столбцы ListBox или ComboBox , кроме одного, можно задать значение ColumnWidths для других столбцов равным нулю и определить отображаемый столбец информации, оставив свойству ColumnWidths значение по умолчанию и используя свойство TextColumn . Когда пользователь выбирает строку, свойству Text элемента управления присваивается значение столбца, определяемого свойством TextColumn . В поле со списком система отображает столбец, назначаемый свойством TextColumn в текстовой части элемента управления.

Аналогичным образом можно указать, какой столбец значений используется для элемента управления, когда пользователь делает выбор, указав номер столбца в свойстве BoundColumn .

См. также

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

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

Источник

How to Set Column Header and Format Columns in VBA ListBox?

I have a userform with one TextBox and One ListBox.

TextBox1 is for type query and ListBox1 for Search Result.

A data sheet is named «DAY BOOK«, where column D and H are a date fields.

Below code works well, but displaying the search result

  • the headerline disappears and
  • date fields are shown as numbers before and after search (How to format the date columns)

also required: First column of the DAY BOOK sheet empty.

As newby any help will be appreciated.

1 Answer 1

Get column header and date formats

Assuming that there is no RowSource bound, as this wouldn’t cooperate with later dynamic array assignments executed in your post, it suffices to insert rowList.Add 1 immediately after code line Set rowList = New Collection to include captions as it will be added as first element to the collection (referring to header row 1).

2.«. and date fields [columns D and H] are shown in numbers»

Assigning range values to a datafield array via .Value2 results in dates shown as numeric values, so e.g. Jan 4th 2021 in column D would be displayed as 44201 .

If it’s only for search matters you could change the code line after section comment ‘Read the values into an array. to v = rng.Value (instead of .Value2 ) displaying the date format due to regional settings, otherwise you’d have to change each single format by a loop through array v respectively the filtered array listItems before populating the listbox.

If you don’t want the first listbox column empty, change the code line after section comment ‘Size the new list array, based on matching items. to

Further hint: naming a variable removeItem if it’s used to include items seems contraproductive.

Источник

VBA Excel Populate ListBox with multiple columns

This may be a cheap question for some but I’m totally confused on how to populate my listbox.

Using this line I can populate the listbox as shown below:
ListBox1.List = Sheets(«Sheet1»).Cells(1, 1).CurrentRegion.Value
or

Below is the data I’m planning to use to populate the list box and is progressive. Only the column has the fix count.

Someone please enlighten me on how to populate a list box adapative to multiple columns and rows using FOR LOOP as shown in my code above. Any help appreciated. Thanks.

2 Answers 2

Methods

  1. It’s always better to loop through an array than a range — it’s much faster.
  2. It’s even faster to create a variant data field array with a one liner instead of redimensioning a predeclared array and fill it in an extra loop as proposed by Siddharth Rout (though a good method 🙂 Note: The code below is based on his Approach referenced in the above comment just to demonstrate the difference.
  3. Fill ListBox1.List with the array (same method, but reverse direction).

Code

Additional hints

Another advantage of the array method — it overcomes the built-in limitation of only 10 columns when using the .AddItem method.

Furthermore, keep in mind that listbox indexing is zero based, so for example you get the e-mail address (column 3, index 2) of your first item row (index 0) via ListBox1.List(0, 2) , whereas the data field array becomes automatically a one based 2-dim array.

You aren’t restricted to use the .List method to get Information out of the listbox, you can reverse the row — column order by using ListBox1.Column» or even create a new array out of it, which remains a 2-dim object, even if there is only ONE item (note: the Application.Transpose` method would redim a 2 dimensional array with only one row to a 1-dim array).

A last point: you can easily dump back again the whole listbox to an Excel sheet via rng = ListBox1.List , but take care to define the correct range.

Источник

In this article I will explain how you can work with a listbox with multiple columns. In the figure below you can see an example of what a multi column listbox would look like:

MultiColumn LIstbox VBA


Creating Multi Column Listboxes:

There are several methods for creating a multi column listbox.

Method 1,  Using the property window:

After inserting a listbox onto the userform, you can define the number of columns using the property window. Change the Column Count Property to the number of columns you wish to have:

Column Count, LIstbox VBA
Method 2, Through VBA Code:

If you don’t know the number of columns you will be needing before runtime, you can set the number of columns using VBA through the ColumnCount property. The code below will create 3 columns for our listbox:

ListBox1.ColumnCount = 3


Modifying Column Width:

Again there are several methods for modifying the width of the columns:

Method 1,  using the property window:

In this method the column widths are defined by modifying the ColumnWidths property in the property windows. The width of each column is separated using a semicolon.  For a listbox with 3 columns, the expression below would change the width of the leftmost column to 30 and the middle column to 20. Note that the last column will take up any space that is left. The values are from left to right:

30;20

MultiColumn Listbox, Column Width, VBA

Note: When working in Excel, the width unit will be in points while in access it will be in inches.

Method 2, Through VBA Code:

Another method for changing the column widths is using VBA at runtime. This is specially useful when you don’t know the size of your columns before running the code. The columns widths can be changed using the ColumnWidths property. The code below will change the width of the left most column to 30 and the next column to 20. The last column will always take up whatever space there is left:

ListBox1.ColumnWidths = "30;20"


Modify Listbox Data:

The items in a multi column listbox can be accessed using the .List member. This member accepts two parameters as input:

ListBox1.List(RowIndex, ColumnIndex)

RowIndex: The row index of the record we want to access. Note the rows in a listbox are zero based. Therefor the index of the first row is “0” (zero).

ColumnIndex: The column index of the field we want to access. Note the columns in a multi column listbox are also zero indexed. Therefore the first column has an index of “0” (zero).

Example: 

Lets say we have a listbox with the following data:

MultiColumn LIstbox VBA
The code below will change the value in the first column of the second row to “NEWNAME”:

ListBox1.List(1, 0) = "NEWNAME"

Result:

The row “Allen Mathews 478-4578” was changed to “NEWNAME Mathews 478-4578”:

MultiColumn Listbox Modify Value


Filling a Multi Column Listbox With Data:

In order to fill a multi column listbox with data there are 2 steps:

Step 1, Create a new row:

This can be done using the code below:

ListBox1.AddItem

Step 2, Modify the new row:

Using the method explained in the previous section the fields of the new row are be modified.

Example:

The code below will do the follwing:

  1. Change ListBox1 to a 4 column listbox.
  2. Modify its column widths
  3. Add values to the 4 columns.

Sub main()
Dim i As Integer
'define 4 column listbox
ListBox1.ColumnCount = 4
'change column widhts
ListBox1.ColumnWidths = "20;40;60"

'assing values to the columns
For i = 1 To 9
    ListBox1.AddItem
    ListBox1.List(i - 1, 0) = i
    ListBox1.List(i - 1, 1) = i * 10
    ListBox1.List(i - 1, 2) = i * 100
    ListBox1.List(i - 1, 3) = i * 1000
Next i
End Sub

Result:

VBA Multicolumn listbox, add rows


Get Selected Items, From Columns:

In order to determine the selected items in a listbox, the .Selected property of the list box could be used:

ListBox1.Selected(RowIndex)

The expression above returns true if the user has selected the row with the index “RowIndex”. One way to determine the selected indices is to loop through all the rows, and use the .Selected property to determine if the current row is selected or not.

After determining if the items is selected or not, you can use the .List member to get the value from the desired column.

Example:

Lets say we have the userform below:

MultiColumn LIstbox VBA
The function below will store the values in the second column of the selected rows in the array, arrLastNames:

Sub Example2()
Dim arrLastName(1 To 100) As String
Dim i As Integer
Dim counter As Integer

counter = 1
'loop through the values in the listbox
For i = 1 To ListBox1.ListCount
    'check if the current value is selected
    If ListBox1.Selected(i - 1) = True Then
        'add the value in the last name column to the
        'array
        arrLastName(counter) = ListBox1.List(i - 1, 1)
        counter = counter + 1
    End If
Next i
End Sub

Assume the following values have been selected in the list box:

VBA Listbox, Selected Items, Multi Column
Result:
Values selected from drop down list

You can download the file and code related to this article from the links below:

  • Listbox_GetSelected.xlsm
  • ListBox_Fill.xlsm

See also:

  • ListBox Object Members (MSDN)

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website www.software-solutions-online.com

Понравилась статья? Поделить с друзьями:
  • Excel vba listbox additem
  • Excel vba for financial modeling
  • Excel vba oleobject add
  • Excel vba list of strings
  • Excel vba for eof