Элемент управления пользовательской формы ListBox для выбора и ввода информации в VBA Excel. Свойства списка, его заполнение, извлечение данных, примеры кода.
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»:
В окне 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 значение из третьего столбца выделенной пользователем строки.
Теперь при выборе строки в списке, значение свойства Value будет записываться в ячейку «F1», а при клике по форме функция MsgBox выведет значение третьего столбца выделенной строки.
Обратите внимание, что при первом запуске формы, когда ячейка «F1» пуста и ни одна строка в ListBox не выбрана, клик по форме приведет к ошибке. Это произойдет из-за того, что свойство ListIndex возвратит значение -1, а это недопустимый номер строки для свойства List.
Если для списка разрешен многострочный выбор (MultiSelect = fmMultiSelectMulti или MultiSelect = fmMultiSelectExtended), тогда, независимо от количества выбранных строк, свойство Value будет возвращать значение Null, а свойство Text – пустую строку. Свойство ListIndex будет возвращать номер строки, которую кликнули последней, независимо от того, что это было – выбор или отмена выбора.
Иногда перед загрузкой в ListBox требуется отобрать уникальные элементы из имеющегося списка. Смотрите, как это сделать с помощью объектов Collection и Dictionary.
In this Article
- Using a VBA ArrayList
- Distributing Your Excel Application Containing an Array List
- Scope of an Array List Object
- Populating and Reading from Your Array List
- Editing and Changing Items in an Array List
- Adding an Array of Values to an Array List
- Reading / Retrieving a Range of Items from an Array List
- Searching for Items Within an Array List
- Insert and Remove Items
- Sorting an Array List
- Cloning an Array List
- Copying a List Array into a Conventional VBA Array Object
- Copying a List Array into a Worksheet Range
- Empty All Items from an Array List
- Array List Methods Summary for Excel VBA
Using a VBA ArrayList
An ArrayList is a VBA object that can be used to store values. It is similar to a Collection object, but it has far greater flexibility from a programming point of view. Let’s discuss some difference between ArrayLists and Collections and Arrays.
- The Collection object only has two methods (Add, Remove) and two properties (Count, Item) whereas an Array List has many more.
- The Collection object is read only. Once values have been added, the indexed value cannot be changed, whereas on an Array List, editing is possible.
- The ArrayList object expands and contracts in size according to how many items that it contains. It does not need to be dimensioned before use like an Array.
- The ArrayList is one dimensional (same as the Collection object) and the default data type is Variant, which means that it will accept any type of data, whether it be numeric, text, or date.
In many ways the Array List addresses a number of shortcomings of the Collection object. It is certainly far more flexible in what it can do.
The Array List object is not part of the standard VBA library. You can use it in your Excel VBA code by using late or early binding.
Sub LateBindingExample()
Dim MyList As Object
Set MyList = CreateObject("System.Collections.ArrayList")
End Sub
Sub EarlyBindingExample()
Dim MyList As New ArrayList
End Sub
In order to use the early binding example, you must first enter a reference in VBA to the file ‘mscorlib.tlb’
You do this by selecting ‘Tools | References ‘ from the Visual Basic Editor (VBE) window. A pop-up window will appear with all available references. Scroll down to ‘mscorlib.dll’ and tick the box next to it. Click OK and that library is now part of your project:
One of the big drawbacks of an Array List object is that it does not have ‘Intellisense’. Normally, where you are using an object in VBA such as a range, you will see a pop-up list of all the available properties and methods. You do not get this with an Array List object, and it sometimes needs careful checking to make sure that you have spelt the method or property correctly.
Also, if you press F2 in the VBE window, and search on ‘arraylist’, nothing will be displayed, which is not very helpful to a developer.
Your code will run considerably faster with early binding, because it is all compiled up front. With late binding, the object has to be compiled as the code runs
Distributing Your Excel Application Containing an Array List
As already pointed out, the ArrayList object is not part of Excel VBA. This means that any of your colleagues that you distribute the application to must have access to the file ‘mscorlib.tlb’
This file is normally located in:
C:WindowsMicrosoft.NETFrameworkv4.0.30319
It could be worth writing some code (using the Dir method) to check that this file exists when a user loads the application so that they experience a ‘soft landing’ if not found. If it is not present, and the code runs then errors will occur.
Also, the user must have the correct .Net Framework version installed. Even if the user has a later version, V3.5 must be installed otherwise your application will not work
Scope of an Array List Object
In terms of scope, the Array List object is only available whilst the workbook is open. It does not get saved when the workbook is saved. If the workbook is re-opened then the Array List object needs to be re-created using VBA code.
If you want your Array List to be available to all the code in your code module, then you need to declare the Array List object in the Declare section at the very top of the module window
This will ensure that all your code within that module can access the Array List. If you want any module within your workbook to access the Array List object, then define it as a global object.
Global MyCollection As New ArrayList
Populating and Reading from Your Array List
The most basic action that you want to take is to create an array list, put some data into it and then prove that the data can be read. All the code examples in this article assume that you are using early binding, and have added ‘mscorlib.tlb’ to the VBA references, as described above.
Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList
'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Iterate through array list to prove values
For N = 0 To MyList.Count - 1
MsgBox MyList(N)
Next N
End Sub
This example creates a new ArrayList object, populates it with 3 items, and the iterates through the list displaying each item.
Note that the ArrayList index starts at 0, not 1, so you need to subtract 1 from the Count value
You can also use a ‘For…Each’ loop to read the values:
Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList
'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Iterate through array list to prove values
For Each I In MyList
MsgBox I
Next I
End Sub
Editing and Changing Items in an Array List
A major advantage of an Array List over a Collection is that the items in the list can be edited and changed within your code. The Collection object is read only whereas the Array List object is read / write.
Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList
'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Change item 1 from ‘Item2’ to ‘Changed’
MyList(1) = "Changed"
'Iterate through array list to prove change worked
For Each I In MyList
'Display item name
MsgBox I
Next I
End Sub
In this example, the second item, ‘Item2’ is altered to the value ‘Changed’ (remember that the index starts at 0). When the iteration is run at the end of the code, the new value will be displayed.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Adding an Array of Values to an Array List
You can enter values into your Array List by using an array containing a list of these values or references to cell values on a worksheet
Sub AddArrayExample()
'Create Array list object
Dim MyList As New ArrayList
'iterate through array values adding them to the array list
For Each v In Array("A1", "A2", "A3")
'Add each array value to list
MyList.Add v
Next
'iterate through array values with worksheet references adding them to the array list
For Each v In Array(Range("A5").Value, Range("A6").Value)
MyList.Add v
Next
'Iterate through array list to prove values
For N = 0 To MyList.Count – 1
'Display list item
MsgBox MyList.Item(N)
Next N
End Sub
Reading / Retrieving a Range of Items from an Array List
By using the GetRange method on an Array List, you can specify a rage of consecutive items to be retrieved. The two parameters required are the starting index position and the number of items to be retrieved. The code populates a second Array List object with the sub set of items which can then be read separately.
Sub ReadRangeExample()
'Define objects
Dim MyList As New ArrayList, MyList1 As Object
'Add items to ‘MyList’ object
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item6"
MyList.Add "Item4"
MyList.Add "Item7"
'Capture 4 items in ‘MyList’ starting at index position 2
Set MyList1 = MyList.GetRange(2, 4)
'Iterate through the object ‘MyList1’ to display the sub set of items
For Each I In MyList1
'Display item name
MsgBox I
Next I
End Sub
Searching for Items Within an Array List
You can test whether a named item is in your list by using the ‘Contains’ method. This will return True or False
MsgBox MyList.Contains("Item2")
You can also find the actual index position by using the ‘IndexOf’ method. You need to specify the start index for the search (usually 0). The return value is the index of the first instance of the found item. You can then use a loop to change the starting point to the next index value to find further instances if there are several duplicate values.
If the value is not found then a value of -1 is returned
This example demonstrates using ‘Contains’, item not found, and looping through the array list to find the position of all duplicate items:
Sub SearchListExample()
'Define array list and variables
Dim MyList As New ArrayList, Sp As Integer, Pos As Integer
'Add new items including a duplicate
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"
'Test for “Item2” being in list - returns True
MsgBox MyList.Contains("Item2")
'Get index of non-existent value – returns -1
MsgBox MyList.IndexOf("Item", 0)
'Set the start position for the search to zero
Sp = 0
'Iterate through list to get all positions of ‘Item1”
Do
'Get the index position of the next ‘Item1’ based on the position in the variable ‘Sp’
Pos = MyList.IndexOf("Item1", Sp)
'If no further instances of ‘Item1’ are found then exit the loop
If Pos = -1 Then Exit Do
'Display the next instance found and the index position
MsgBox MyList(Pos) & " at index " & Pos
'Add 1 to the last found index value – this now becomes the new start position for the next search
Sp = Pos + 1
Loop
End Sub
Note that the search text used is case sensitive and wild cards are not accepted.
VBA Programming | Code Generator does work for you!
Insert and Remove Items
If you do not wish to add your items onto the end of the list, you can insert them at a particular index position so that the new item is in the middle of the list. The index numbers will be automatically adjusted for the subsequent items.
Sub InsertExample()
'Define array list object
Dim MyList As New ArrayList
'Add items to array list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"
'Insert ‘Item6’ at index position 2
MyList.Insert 2, "Item6"
'Iterate through items in the array list to show new order and index position
For N = 0 To MyList.Count - 1
MsgBox MyList(N) & " Index " & N
Next N
End Sub
In this example, ‘Item6’ is added into the list at index position 2, so the ‘item3’ which was at index position 2 now moves to index position 3.
An individual item can be removed by using the ‘Remove’ method.
MyList.Remove "Item"
Note that there is no error produced if the item name is not found. All the subsequent index numbers will be changed to suit the removal.
If you know the index position of the item you can use the ‘RemoveAt’ method e.g.
MyList.RemoveAt 2
Note that if the index position given is greater than the number of items in the array list, then an error will be returned.
You can remove a range of values from the list by using the ‘RemoveRange’ method. The parameters are the starting index and then the number of items to remove e.g.
MyList.RemoveRange 3, 2
Note that you will get an error in your code if the number of items offset from the start value is greater than the number of items in the array list.
In both the ‘RemoveAt’ and ‘RemoveRange’ methods, some code would be advisable to check whether the index numbers specified are greater than the total number of items in the array list in order to trap any possible errors. The ‘Count’ property will give the total number of items in the array list.
Sub RemoveExample()
'Define array list object
Dim MyList As New ArrayList
'Add items to array list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"
MyList.Add "Item4"
MyList.Add "Item5"
'Insert ‘Item6’ at index position 2
MyList.Insert 2, "Item6"
'Remove ‘Item2’
MyList.Remove "Item2"
'Remove ‘Item’ – this does not exist in the array list but does not error
MyList.Remove "Item"
'Remove the item at index position 2
MyList.RemoveAt 2
'Remove 2 consecutive items starting at index position 2
MyList.RemoveRange 3, 2
'Iterate through the array list to show what is left and what index position it is now in
For N = 0 To MyList.Count - 1
MsgBox MyList(N) & " Index " & N
Next N
End Sub
Note that if you are using the ‘RemoveAt’ to remove an item at a specific position then as soon as that item is removed, all the subsequent index positions are altered. If you have multiple removals using the index position, then a good idea is to start with the highest index number and step backwards down to position zero so that you will always be removing the correct item. In this way you will not have the problem
Sorting an Array List
Another big advantage over a collection is that you can sort the items into ascending or descending order.
The Array List object is the only object in Excel VBA with a sorting method. The sorting method is very fast and this can be an important consideration for using an Array List.
In the collection object, some ‘out of the box’ thinking was required to sort all the items, but with an array list, it is very simple.
The ‘Sort’ method sorts in ascending order, and the ‘Reverse’ method sorts in descending order.
Sub ArrayListExample()
'Create Array List object
Dim MyList As New ArrayList
'Add items in a non-sorted order
MyList.Add "Item1"
MyList.Add "Item3"
MyList.Add "Item2"
'Sort the items into ascending order
MyList.Sort
'Iterate through the items to show ascending order
For Each I In MyList
'Display item name
MsgBox I
Next I
'Sort the items into descending order
MyList.Reverse
'Iterate through the items to show descending order
For Each I In MyList
'Display item name
MsgBox I
Next I
End Sub
Cloning an Array List
An array list has the facility to create a clone or copy of itself. This is useful if a user makes changes to the items using a front end and your VBA code, but you need to keep a copy of the items in their original state as a backup.
This could provide the user with an ‘Undo’ feature. They may have made the changes, and wish to revert back to the original list.
Sub CloneExample()
'Define two objects – array list and an object
Dim MyList As New ArrayList, MyList1 As Object
'Populate first object with items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Copy Mylist to MyList1
Set MyList1 = MyList.Clone
'Iterate through MyList1 to prove cloning
For Each I In MyList1
'Display item name
MsgBox I
Next I
End Sub
‘MyList1’ now contains all the items from ‘MyList’ in the same order
Copying a List Array into a Conventional VBA Array Object
You can use a simple method to copy the array list into a normal VBA array:
Sub ArrayExample()
'Create array list object and a standard array object
Dim MyList As New ArrayList, NewArray As Variant
'Populate array list with items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Copy the array list to the new array
NewArray = MyList.ToArray
'Iterate through the new array – note that the array list count provides the maximum index
For N = 0 To MyList.Count – 1
'Display item name
MsgBox NewArray(N)
Next N
End Sub
Copying a List Array into a Worksheet Range
You can copy your array list to a specific worksheet and cell reference without the need to iterate through the array list. You need only specify the first cell reference
Sub RangeExample()
'Create new array list object
Dim MyList As New ArrayList
'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Clear the target sheet
Sheets("Sheet1").UsedRange.Clear
'Copy items across a row
Sheets("Sheet1").Range("A1").Resize(1, MyList.Count).Value = MyList.toArray
'Copy items down a column
Sheets("Sheet1").Range("A5").Resize(MyList.Count, 1).Value = _
WorksheetFunction.Transpose(MyList.toArray)
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Empty All Items from an Array List
There is a simple function (Clear) to clear the array list completely
Sub ClearListExample()
'Create array list object
Dim MyList As New ArrayList
'Add new items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Show count of items
MsgBox MyList.Count
'Clear all items
MyList.Clear
'Show count of items to prove that clear has worked
MsgBox MyList.Count
End Sub
This example creates items in an array list and then clears the array list. Message boxes prove before and after the number of items in the array list.
Array List Methods Summary for Excel VBA
Task | Parameters | Examples |
Add / Edit item | Value | MyList.Add “Item1” |
MyList(4)= “Item2” | ||
Clone an Array List | None | Dim MyList As Object |
Set MyList2 = MyList.Clone | ||
Copy to Array | None | Dim MyArray As Variant |
MyArray = MyList.ToArray | ||
Copy to a worksheet range(row) | None | Sheets(“Sheet1”).Range(“A1”).Resize(1, MyList.Count).Value = MyList.ToArray |
Copy to a worksheet range(column) | None | Sheets(“Sheet1”).Range(“A3”).Resize(MyList.Count, 1).Value = WorksheetFunction.Transpose(MyList.ToArray) |
Create | “System.Collections.ArrayList” | Dim MyList As Object |
Set MyList = CreateObject(“System.Collections.ArrayList”) | ||
Declare | N/A | Dim MyList As Object |
Find / check if item exists | Item to find | MyList.Contains(“Item2”) |
Find the position of an item in the ArrayList | 1. Item to find. | Dim IndexNo As Long |
2. Position to start searching from. | IndexNo = MyList.IndexOf(“Item3”, 0) | |
IndexNo = MyList.IndexOf(“Item5”, 3) | ||
Get number of items | None | MsgBox MyList.Count |
Insert Item | 1. Index – position to insert at. | MyList.Insert 0, “Item5” |
2 Value – object or value to insert. | MyList.Insert 4, “Item7” | |
Read item | Index – long integer | MsgBox MyList.Item(0) |
MsgBox MyList.Item(4) | ||
Read item added last | Index – long integer | MsgBox MyList.Item(list.Count – 1) |
Read item added first | Index – long integer | MsgBox MyList.Item(0) |
Read all items(For Each) | N/A | Dim element As Variant |
For Each element In MyList | ||
MsgBox element | ||
Next element | ||
Read all items(For) | Index – long integer | Dim i As Long |
For i = 0 To MyList.Count – 1 | ||
MsgBox i | ||
Next i | ||
Remove all Items | None | MyList.Clear |
Remove item at position | Index position where the item is | MyList.RemoveAt 5 |
Remove item by name | The item to remove from the ArrayList | MyList.Remove “Item3” |
Remove a range of Items | 1. Index – starting postion. | MyList.RemoveRange 4,3 |
2. Count – the number of items to remove. | ||
Sort in Descending Order | None | MyList.Reverse |
Sort in ascending order | Non | MyList.Sort |
The VBA ArrayList is a much better alternative to the built-in VBA Collection. It contains much richer functionality such as sorting, converting to an array, removing all items etc.
Check out the quick guide for an overview of what the ArrayList does. The rest of this post provides examples of how to use the ArrayList.
Quick Guide to the VBA ArrayList
Task | Method | Parameters | Examples |
---|---|---|---|
Access item | Item | index — long integer | value = list.Item(0) value = list.Item(3) |
Access item added last | Item | index — long integer | value = list.Item(list.Count — 1) |
Access item added first | Item | index — long integer | value = list.Item(0) |
Access all items(For Each) | N/A | N/A | Dim element As Variant For Each element In fruit Debug.Print element Next element |
Access all items(For) | Item | index — long integer | Dim i As Long For i = 0 To list.Count — 1 Debug.Print list.item(i) Next i |
Add item | Add | object or value | list.Add «Apple» list.Add «Pear» |
Copy ArrayList to another ArrayList | Clone | None | Dim list2 As Object Set list2 = list.Clone |
Copy to Array | ToArray | None | Dim arr As Variant arr = list.ToArray |
Copy to a range(row) | ToArray | None | Sheet1.Range(«A1»).Resize(1, list.Count).Value = list.ToArray |
Copy to a range(column) | ToArray | None | Sheet1.Range(«A3»).Resize(list.Count, 1).Value = WorksheetFunction.Transpose(list.ToArray) |
Create | CreateObject | «System.Collections.ArrayList» | Dim list As Object Set list = CreateObject(«System.Collections.ArrayList») |
Declare | N/A | N/A | Dim list As Object |
Find — check if item exists | Contains | item to find | list.Contains(«Apple») |
Find the position of an item in the ArrayList | IndexOf | 1. Item to find. 2. Position to start searching from. |
Dim index As Long ‘ Search from 0 position index = fruit.IndexOf(«Pear», 0) |
Get number of items | Count | None | totalElements = list.Count |
Insert Item | Insert | 1. Index — position to insert at. 2 Value — object or value to insert. |
list.Insert 0, «Peach» ‘ First list.Insert 1, «Banana» ‘ Second list.Insert list.Count, «Orange» ‘ Last |
Remove all Items | Clear | None | list.Clear |
Remove item at position | RemoveAt | Index — position where the item is | list.RemoveAt 0 |
Remove item by name | Remove | Item — the item to remove from the ArrayList | list.Remove «Apple» |
Remove a range of Items | RemoveRange | 1. Index — starting postion. 2. Count — the number of items to remove. |
list.RemoveRange 1,3 |
Reverse the list | Reverse | None | list.Reverse |
Sort in ascending | Sort | None | list.Sort |
Description
The ArrayList is similar to the VBA built-in Collection. It is not part of VBA, but it is in an external library which we can access easily. The ArrayList is the same one that is used in the language C#. As you would expect, the ArrayList has a built-in sort, array conversion and other functionality that you would expect in a modern programming language. For the purpose of this article, I will refer to it as the VBA ArrayList.
Download the Source Code
Declare and Create the VBA ArrayList
Like all external libraries we can create the ArrayList using early and late binding.
Late Binding
We use CreateObject to create the ArrayList using late binding:
' https://excelmacromastery.com/ Sub UsingArrayList() Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") End Sub
The disadvantage of late binding is that we don’t have access to the Intellisense. The advantage is that it is better to use when distributing a VBA application to a user.
Early Binding
Update 12-Nov-2019: Intellisense doesn’t currently work for the ArrayList.
Early binding allows use to use the Intellisense to see what is available to use. We must first add the type library as a reference and then select it from the reference list. We can use the following steps to do this:
- Select Tools and then References from the menu.
- Click on the Browse.
- Find the file mscorlib.tlb and click Open. It should be in a folder like this C:WindowsMicrosoft.NETFrameworkv4.0.30319.
- Scroll down the list and check mscorlib.dll.
- Click Ok.
You can now use the following code to declare the ArrayList using early binding:
Dim coll As New ArrayList
VBA ArrayList Automation Error
You may encounter the VB Run-time Error ‘-2146232576 Automation Error’ when trying to get the ArrayList to work. Or sometimes your code has been working for a long time and then suddenly this error appears.
This is caused by not having the correct .Net Framework version installed. The correct version is 3.5. It doesn’t matter if you have a later version like 4.7, you must have 3.5 installed.
Adding Items to the VBA ArrayList
Adding items to the ArrayList is very similar to how we add them to the Collection. We use the Add method:
' https://excelmacromastery.com/ Sub AddingToList() Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") ' Add items coll.Add "Apple" coll.Add "Watermelon" coll.Add "Pear" coll.Add "Banana" ' Insert to first position coll.Insert 0, "Plum" End Sub
Reading through an ArrayList
We read through the ArrayList similar to the VBA Collection except that we read from zero to Count-1 rather than from one to Count.
Note: We will use this PrintToImmediateWindow sub in the follow examples to show the contents of the array after the various operations.
' Print all items to the Immediate Window(Ctrl + G) ' Items must be basic data type e.g. Long, String, Double ' https://excelmacromastery.com/ Sub PrintToImmediateWindow(coll As Object) Dim i As Long For i = 0 To coll.Count - 1 Debug.Print coll(i) Next i End Sub
We can use the For Each loop with the VBA ArrayList just like we use it with a Collection:
' Print all items to the Immediate Window(Ctrl + G) ' Items much be basic data type e.g. Long, String, Double ' https://excelmacromastery.com/ Sub PrintToImmediateWindowEach(coll As Object) Dim item As Variant For Each item In coll Debug.Print item Next item End Sub
You can download all the code examples at the top of this post.
Sorting
Sort will sort the VBA ArrayList in ascending order.
To sort in descending order simply use Reverse after Sort.
The following code shows an example of sorting in both ascending and descending order:
' https://excelmacromastery.com/ Sub Sorting() Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") ' Add items coll.Add "Apple" coll.Add "Watermelon" coll.Add "Pear" coll.Add "Banana" coll.Add "Plum" ' Sort coll.Sort Debug.Print vbCrLf & "Sorted Ascending" ' Add this sub from "Reading through the items" section PrintToImmediateWindow coll ' Reverse sort coll.Reverse Debug.Print vbCrLf & "Sorted Descending" PrintToImmediateWindow coll End Sub
' https://excelmacromastery.com/ Sub PrintToImmediateWindow(coll As Object) Dim i As Long For i = 0 To coll.Count - 1 Debug.Print coll(i) Next i End Sub
Cloning the VBA ArrayList
We can create a copy of the ArrayList by using the Clone method. This creates a brand new copy of the ArrayList.
It’s not the same as assigning the variable which means both variables point to the same ArrayList e.g.
' Both variables point to the same ArrayList Set coll2 = coll
We use Clone like this:
' https://excelmacromastery.com/ Sub Cloning() ' Create the ArrayList Dim coll1 As Object Set coll1 = CreateObject("System.Collections.ArrayList") ' Add items coll1.Add "Apple" coll1.Add "Watermelon" coll1.Add "Pear" coll1.Add "Banana" coll1.Add "Plum" ' Creates a copy of the original ArrayList Dim coll2 As Object Set coll2 = coll1.Clone ' Remove all items from coll1 coll1.Clear ' Add PrintToImmediateWindow sub from "Reading through the items" section Debug.Print vbCrLf & "coll1 Contents are:" PrintToImmediateWindow coll1 Debug.Print vbCrLf & "coll2 Contents are:" PrintToImmediateWindow coll2 End Sub
' https://excelmacromastery.com/ Sub PrintToImmediateWindow(coll As Object) Dim i As Long For i = 0 To coll.Count - 1 Debug.Print coll(i) Next i End Sub
Copying from an VBA ArrayList to an Array
We can copy from the ArrayList to an array in one line using the ToArray method:
' https://excelmacromastery.com/ Sub CopyToArray() ' Declare and Create ArrayList Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") ' Add items coll.Add "Apple" coll.Add "Watermelon" coll.Add "Pear" coll.Add "Banana" coll.Add "Plum" ' Copy to array Dim arr As Variant arr = coll.ToArray ' Print the array Debug.Print vbCrLf & "Printing the array contents:" PrintArrayToImmediate arr End Sub
' Prints the contents of a one dimensional array ' to the Immediate Window(Ctrl + G) ' https://excelmacromastery.com/ Sub PrintArrayToImmediate(arr As Variant) Dim i As Long For i = LBound(arr) To UBound(arr) Debug.Print arr(i) Next i End Sub
You can download all the code examples at the top of this post.
Writing Directly to a Range
One of the biggest advantages of the ArrayList is that we can write the contents directly to a range.
The code below writes the contents to both a row and a column:
' Writes the contents of an ArrayList to a worksheet range ' https://excelmacromastery.com/ Sub ClearArrayList() ' Declare and Create ArrayList Dim fruit As Object Set fruit = CreateObject("System.Collections.ArrayList") ' Add items fruit.Add "Apple" fruit.Add "Watermelon" fruit.Add "Pear" fruit.Add "Banana" fruit.Add "Plum" fruit.Add "Peach" ' ' Clean existing data Sheet1.Cells.ClearContents ' Write to a row Sheet1.Range("C1").Resize(1, fruit.Count).Value = fruit.toArray ' Write to a column Sheet1.Range("A1").Resize(fruit.Count, 1).Value = WorksheetFunction.Transpose(fruit.toArray) End Sub
Array to a VBA ArrayList(1D)
As we have seen, there is an in-built function ToArray which will copy from an ArrayList to an Array.
If we want to copy from an Array to an ArrayList we need to create our own function which I have done below. Because we read through the items one at a time, it may be a bit slow if we have a lot of data:
' https://excelmacromastery.com/ Function ArrayToArrayList(arr As Variant) As Object ' Check that array is One Dimensional On Error Resume Next Dim ret As Long ret = -1 ret = UBound(arr, 2) On Error Goto 0 If ret <> -1 Then Err.Raise vbObjectError + 513, "ArrayToArrayList" _ , "The array can only have one 1 dimension" End If ' Create the ArrayList Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") ' Add items to the ArrayList Dim i As Long For i = LBound(arr, 1) To UBound(arr, 1) coll.Add arr(i) Next i ' Return the new ArrayList Set ArrayToArrayList = coll End Function
You can use it like this:
' https://excelmacromastery.com/ Sub ReadFromArray1D() Dim arr(1 To 3) As Variant arr(1) = "PeterJ" arr(2) = "Jack" arr(3) = "Jill" ' Create the ArrayList Dim coll As Object Set coll = ArrayToArrayList(arr) PrintToImmediateWindow coll End Sub
Remove All Items from the ArrayList
We can remove all the items from an ArrayList by using the Clear function:
' https://excelmacromastery.com/ Sub ClearArrayList() ' Declare and Create ArrayList Dim coll As Object Set coll = CreateObject("System.Collections.ArrayList") ' Add items coll.Add "Apple" coll.Add "Watermelon" coll.Add "Pear" coll.Add "Banana" coll.Add "Plum" Debug.Print vbCrLf & "The number of items is: " & coll.Count ' Remove all item coll.Clear Debug.Print "The number of items is: " & coll.Count End Sub
You can download all the code examples at the top of this post.
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 the The Ultimate 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 VBA, we have built-in collections of data types, function variables, and other important statements. But, we have an ArrayList in VBA in which users can modify and put their collections of variables and user-defined functions in an array. There are certain keywords for the array list to design it.
Table of contents
- Excel VBA ArrayList
- Examples of VBA ArrayList in Excel
- Example #1 – Create Instance of VBA ArrayList
- Example #2 – Store Values to Cells Using VBA ArrayList
- Recommended Articles
- Examples of VBA ArrayList in Excel
Excel VBA ArrayList
VBA ArrayList is a kind of data structure we use in VBA to store the data. For example, ArrayList in Excel VBA is a class that creates an array of values. However, unlike traditional arrays, where those arrays have a fixed length, Array List does not have any fixed length.
VBA ArrayList is not part of the VBA list. Rather, it is an external library or object which we need to set the reference before we start accessing it.
Arrays in VBAA VBA array in excel is a storage unit or a variable which can store multiple data values. These values must necessarily be of the same data type. This implies that the related values are grouped together to be stored in an array variable.read more are an integral part of any coding language. For example, using arrays in excelArray formulas are extremely helpful and powerful formulas that are used in Excel to execute some of the most complex calculations. There are two types of array formulas: one that returns a single result and the other that returns multiple results.read more, we can store data with a single variable name by declaring the “lower limit & upper limit.”
With regular arrays, we need to decide the lower limit and upper limit of the array. Therefore, we need to decide well in advance when declaring the variable in the case of static arrays. In the case of dynamic arrays, we need to decide the array’s length after declaring the array by using the “ReDim” statement in VBA.
However, we have one more option: store the “N” number of values without declaring the lower and upper limits. This article will show you that option, i.e., VBA ArrayList.”
Follow the steps below to set the reference to the VBA ArrayList object.
- Go to “Tools” > “References.”
- Object library reference window will appear in front of you. Select the option “mscorlib.dll.”
- Click on “OK.” Now, we can access the VBA ArrayList.
Examples of VBA ArrayList in Excel
Below are the examples of Excel VBA ArrayList.
You can download this VBA ArrayList Excel Template here – VBA ArrayList Excel Template
Example #1 – Create Instance of VBA ArrayList
Since Excel VBA ArrayList is an external object, we need to create an instance to start using this. To create an instance, follow the below steps.
Step 1: Declare the variable as “ArrayList.”
Code:
Sub ArrayList_Example1() Dim ArrayValues As ArrayList End Sub
Step 2: Since the ArrayList is an object, we need to create a new instance.
Code:
Sub ArrayList_Example1() Dim ArrayValues As ArrayList Set ArrayValues = New ArrayList End Sub
Step 3: We can keep storing values to the array variable using the “Add” method. In the below image, I have added three values.
Code:
Sub ArrayList_Example1() Dim ArrayValues As ArrayList Set ArrayValues = New ArrayList ArrayValues.Add "Hello" 'First Value ArrayValues.Add "Good" 'Second Value ArrayValues.Add "Morning" 'Three Value End Sub
Now, we have assigned three values. How do we identify which is the first, and how can we show the values or use them for our needs?
If you remember the traditional array type, we refer to the first array value like this “ArrayName(0).”
Similarly, we can use the same technique here, as well.
ArrayValue(0) = “Hello”
ArrayValue(1) = “Good”
ArrayValue(2) = “Morning”
Let’s show this in the message box.
Code:
Sub ArrayList_Example1() Dim ArrayValues As ArrayList Set ArrayValues = New ArrayList ArrayValues.Add "Hello" 'First Value ArrayValues.Add "Good" 'Second Value ArrayValues.Add "Morning" 'Three Value MsgBox ArrayValues(0) & vbNewLine & ArrayValues(1) & vbNewLine & ArrayValues(2) End Sub
Now, run the code using the F5 key or manually. Then, we will see “Hello,” “Good,” and “Morning” in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
Like this, we can store any number of values with an Array List Object.
Example #2 – Store Values to Cells Using VBA ArrayList
Let’s see the example of storing the assigned values to the cells in the worksheet. Now, look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.
Code:
Sub ArrayList_Example2() Dim MobileNames As ArrayList, MobilePrice As ArrayList Dim i As Integer Dim k As Integer Set MobileNames = New ArrayList 'Names of the mobile MobileNames.Add "Redmi" MobileNames.Add "Samsung" MobileNames.Add "Oppo" MobileNames.Add "VIVO" MobileNames.Add "LG" Set MobilePrice = New ArrayList MobilePrice.Add 14500 MobilePrice.Add 25000 MobilePrice.Add 18500 MobilePrice.Add 17500 MobilePrice.Add 17800 End Sub
We have stored the names of the mobile and prices of the mobile with two array lists. Now, we need to insert these values into the worksheet for this. We need to use loops. The below loop will do the job for me.
Below is the overall code to store values on the worksheet.
Code:
Sub ArrayList_Example2() Dim MobileNames As ArrayList, MobilePrice As ArrayList Dim i As Integer Dim k As Integer Set MobileNames = New ArrayList 'Names of the mobile MobileNames.Add "Redmi" MobileNames.Add "Samsung" MobileNames.Add "Oppo" MobileNames.Add "VIVO" MobileNames.Add "LG" Set MobilePrice = New ArrayList MobilePrice.Add 14500 MobilePrice.Add 25000 MobilePrice.Add 18500 MobilePrice.Add 17500 MobilePrice.Add 17800 k = 0 For i = 1 To 5 Cells(i, 1).Value = MobileNames(k) Cells(i, 2).Value = MobilePrice(k) k = k + 1 Next i End Sub
When we run the code manually or using the F5 key, we will get the result below.
Recommended Articles
This article has been a guide to VBA ArrayList. Here, we learn how to create an ArrayList in VBA, which we can use to store data and simple to advanced examples. Below are some useful Excel articles related to VBA: –
- Excel VBA Debug Print
- VBA UCase
- Text Box in VBA
- Excel VBA Declare Array
Fill the values
array in with the appropriate values from Codes!$A$1:$A$14
.
Code without comments
Sub UpdateLookups()
Dim data, values As Variant
Dim Target As Range
Dim x As Long
values = Array("Tom", "Henry", "Frank", "Richard", "Rodger", "ect...")
With Worksheets("Sheet1")
Set Target = .Range("D2", .Range("D" & .Rows.Count).End(xlUp))
End With
data = Target.Value
For x = 1 To UBound(data, 1)
data(x, 1) = IIf(IsError(Application.Match(data(x, 1), values, 0)), "YES", "NO")
Next
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Target.Offset(0, -3).Value = data
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = False
End Sub
Code with comments
Sub UpdateLookups()
Dim data, values As Variant
Dim Target As Range
Dim x As Long
'values: Array of values that will be searched
values = Array("Tom", "Henry", "Frank", "Richard", "Rodger", "ect...")
'With Worksheets allows use to easily 'qualify' ranges
'The term fully qualified means that there is no ambiguity about the reference
'For instance this referenece Range("A1") changes depending on the ActiveSheet
'Worksheet("Sheet1").Range("A1") is considered a qualified reference.
'Of course Workbooks("Book1.xlsm").Worksheet("Sheet1").Range("A1") is fully qualified but it is usually overkill
With Worksheets("Sheet1")
'Sets a refernce to a Range that starts at "D2" extends to the last used cell in Column D
Set Target = .Range("D2", .Range("D" & .Rows.Count).End(xlUp))
End With
' Assigns the values of the Target Cells to an array
data = Target.Value
'Iterate over each value of the array changing it's value based on our formula
For x = 1 To UBound(data, 1)
data(x, 1) = IIf(IsError(Application.Match(data(x, 1), values, 0)), "YES", "NO")
Next
Application.ScreenUpdating = False 'Speeds up write operations (value assignments) and formatting
Application.Calculation = xlCalculationManual 'Speeds up write operations (value assignments)
'Here we assign the data array back to the Worksheet
'But we assign them 3 Columns to the left of the original Target Range
Target.Offset(0, -3).Value = data
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = False
'Loading the data into an Array allows us to write the data back to the worksheet in one operation
'So if there was 100K cells in the Target range we would have
'reduced the number of write operations from 100K to 1
End Sub