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
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.)
I would use a simple VBA-Collection
and add items with key. The key would be the item itself and because there can’t be duplicit keys the collection will contain unique values.
Note: Because adding duplicit key to collection raises error wrap the call to collection-add into a on-error-resume-next.
The function GetUniqueValues
has source-range-values as parameter and retuns VBA-Collection
of unique source-range-values. In the main
method the function is called and the result is printed into Output-Window. HTH.
Sample source range looked like this:
Option Explicit
Sub main()
Dim uniques As Collection
Dim source As Range
Set source = ActiveSheet.Range("A2:F6")
Set uniques = GetUniqueValues(source.Value)
Dim it
For Each it In uniques
Debug.Print it
Next
End Sub
Public Function GetUniqueValues(ByVal values As Variant) As Collection
Dim result As Collection
Dim cellValue As Variant
Dim cellValueTrimmed As String
Set result = New Collection
Set GetUniqueValues = result
On Error Resume Next
For Each cellValue In values
cellValueTrimmed = Trim(cellValue)
If cellValueTrimmed = "" Then GoTo NextValue
result.Add cellValueTrimmed, cellValueTrimmed
NextValue:
Next cellValue
On Error GoTo 0
End Function
Output
SGD
PHP
KRW
CNY
IDA
BGN
PDSS
CBBT
INPC
DBS
a
In case when the source range consists of areas get the values of all the areas first.
Public Function GetSourceValues(ByVal sourceRange As Range) As Collection
Dim vals As VBA.Collection
Dim area As Range
Dim val As Variant
Set vals = New VBA.Collection
For Each area In sourceRange.Areas
For Each val In area.Value
If val <> "" Then _
vals.Add val
Next val
Next area
Set GetSourceValues = vals
End Function
Source type is now Collection but then all works the same:
Dim uniques As Collection
Dim source As Collection
Set source = GetSourceValues(ActiveSheet.Range("A2:F6").SpecialCells(xlCellTypeVisible))
Set uniques = GetUniqueValues(source)
Excel VBA ArrayList
Data structures are used to store a series of data in programming languages. It binds to the memory rather than address. An ArrayList is one of the data structures in excel. Comparing to normal arrays in excel ArrayList is dynamic. Therefore, no initial declaration of size is needed. ArrayList is not a part of VBA it is associated with an external library which can be used with VBA.
ArrayList can be defined as a list of a nearby memory location. Where the values are retrieved using the index numbers. The list starts from an index number ‘0’, the first element will be inserted into the ‘0’ index and rest is followed by 1, 2, 3, etc. ArrayList offers plenty of built-in operations, sorting, adding, removing, reversing, etc. are some among them.
Adding the Library
To use the ArrayList into the VBA it needs to include the library ‘mscorlib.dll’ which comes with .NET framework.
- Press F11 or right-click the sheet name to get the code window. Go to the VBA code window, from the main menu select Tools.
- The tools menu contains ‘references’ option and it consists of a list of libraries which supports VBA for including different objects. Click on the Reference option.
- It will lead you to a window with a list of different libraries which supports in VBA and Excel. Scroll down to find the ‘dll’. Tick mark to confirm the selection then press ‘OK’ button.
Now the library is included in your VBA code and it will support different methods associated with an ArrayList.
How to Create VBA ArrayList in Excel?
Below are the different examples to create VBA ArrayList in Excel.
You can download this VBA ArrayList Excel Template here – VBA ArrayList Excel Template
Excel VBA ArrayList – Example #1
How to Add Values to the ArrayList using VBA?
ArrayList act as a list where we can add values. This will automatically store in the different portions starting from 0,1, 2, etc. The values can add or insert to the ArrayList using the add method.
In this example, you will learn how to add a list of values into an ArrayList. Follow the below steps to add ArrayList using VBA Code in excel.
Step 1: To add a list of values to an ArrayList create a function arraylist1.
Code:
Private Sub arraylist1() End Sub
Step 2: Now we want to include the ArrayList into the function as an object where a list is declared as an ArrayList.
Code:
Private Sub arraylist1() Dim alist As ArrayList End Sub
Step 3: Since this is an object to use it, you have to create an instance of the ArrayList. Set a new instance for this object.
Code:
Private Sub arraylist1() Dim alist As ArrayList Set alist = New ArrayList End Sub
Step 4: Now using the ‘Add’ property of an ArrayList adds the values to the ArrayList. Where the list is added into the index values in an order 0,1,2,3 etc.
Code:
Private Sub arraylist1() Dim alist As ArrayList Set alist = New ArrayList alist.Add "192" 'index(0) alist.Add "168" 'index(1) alist.Add "1" 'index(2) alist.Add "240" 'index(3) End Sub
Step 5: To check whether the values got added into the list, let’s print the array values using a message box. To print the values each index is printed since the values are stored in these partitions.
Code:
Private Sub arraylist1() Dim alist As ArrayList Set alist = New ArrayList alist.Add "192" 'index(0) alist.Add "168" 'index(1) alist.Add "1" 'index(2) alist.Add "240" 'index(3) MsgBox ("\" & alist(0) & "." & alist(1) & "." & alist(2) & "." & alist(3)) End Sub
Step 6: Press F5 or run button to run the program and the values will be printed as below. Here an IP address is stored in the ArrayList and while printing the values extra notations are concatenated to form the IP address in a proper format.
Automation error in VBA
It is a common error happens while running an ArrayList. An automation error may encounter ‘Run-time Error ‘-2146232576 (80131700) Automation Error’
This is because of not the correct version of the .NET framework installed. To work with ArrayList you must have minimum .NET 3.5 or the higher versions of .NET framework.
Excel VBA ArrayList – Example #2
Sorting ArrayList Using VBA Code
ArrayList supports different functions like sorting, reversing, etc. this help to sort the values inserted into an ArrayList. Once you add a list into the ArrayList it is possible to reverse the inserted list.
Follow the below steps to sort the ArrayList using VBA Code:
Step 1: Create a function called arraysort1 to perform the sorting within the inserted values into an ArrayList.
Code:
Sub arraysort1() End Sub
Step 2: Declare an object ‘arraysort’ of the ArrayList. Use this object to add and sort the values within the ArrayList.
Code:
Sub arraysort1() Dim arraysort As ArrayList End Sub
Step 3: Similar to the first example need to create a new instance of the declared object. Set this instance as a new ArrayList.
Code:
Sub arraysort1() Dim arraysort As ArrayList Set arraysort = New ArrayList End Sub
Step 4: Now using the ‘Add’ method insert the elements to the ArrayList. Which is not possessing any order on values. Randomly inserted some values into the list.
Code:
Sub arraysort1() Dim arraysort As ArrayList Set arraysort = New ArrayList arraysort.Add "13" arraysort.Add "21" arraysort.Add "67" arraysort.Add "10" arraysort.Add "12" arraysort.Add "45" End Sub
Step 5: To note the difference in the ArrayList, let’s print the ArrayList after inserting the values and before sorting it.
Code:
Sub arraysort1() Dim arraysort As ArrayList Set arraysort = New ArrayList arraysort.Add "13" arraysort.Add "21" arraysort.Add "67" arraysort.Add "10" arraysort.Add "12" arraysort.Add "45" MsgBox (arraysort(0) & vbCrLf & arraysort(1) _ & vbCrLf & arraysort(2) & vbCrLf & arraysort(3) _ & vbCrLf & arraysort(4) & vbCrLf & arraysort(5)) End Sub
Step 6: Press F5 on the keyboard or run button on the code window to run the program to print the ArrayList. The ArrayList is printed in the same order as it is inserted since we use the index numbers in its correct order.
Step 7: Now to this list apply the sort property of the ArrayList. Use the sort method to sort the inserted list. The sort property will sort the list of values in ascending order by default.
Code:
Sub arraysort1() Dim arraysort As ArrayList Set arraysort = New ArrayList arraysort.Add "13" arraysort.Add "21" arraysort.Add "67" arraysort.Add "10" arraysort.Add "12" arraysort.Add "45" arraysort.Sort MsgBox (arraysort(0) & vbCrLf & arraysort(1) _ & vbCrLf & arraysort(2) & vbCrLf & arraysort(3) _ & vbCrLf & arraysort(4) & vbCrLf & arraysort(5)) End Sub
Step 8: Hit F5 or Run button under VBE to run this code, Where the values are sorted and printed in order from smallest value to largest.
Excel VBA ArrayList – Example #3
Reversing the ArrayList using VBA Code
When you want to reverse the order of inserted values in an ArrayList reverse method is available. This will reverse the order of the list from its current order. Now we have already sorted the ArrayList in the previous example, which is in ascending order.
Let’s try to reverse the sorted array to make it descending order. Use the reverse method of ArrayList to do this.
Code:
Sub arraysort2() Dim arraysort As ArrayList Set arraysort = New ArrayList arraysort.Add "13" arraysort.Add "21" arraysort.Add "67" arraysort.Add "10" arraysort.Add "12" arraysort.Add "45" arraysort.Sort arraysort.Reverse MsgBox (arraysort(0) & vbCrLf & arraysort(1) _ & vbCrLf & arraysort(2) & vbCrLf & arraysort(3) _ & vbCrLf & arraysort(4) & vbCrLf & arraysort(5)) End Sub
After applying the reverse method, the ArrayList will become in descending order and use the message box to print the reversed array. The sorted list is changed from large value to small value.
Things to Remember
- ArrayList is dynamic in nature; it does not require re-initialization.
- Different built-in methods are associated with ArrayList.
- Compared to the array, ArrayList is easy to use in Excel VBA.
- The supporting .NET libraries should be included in the VBA to work with ArrayList.
- ArrayList is a continuing memory location which identified using index values.
Recommended Articles
This is a guide to VBA ArrayList. Here we discuss how to create ArrayList in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA Arrays
- VBA Sort
- VBA XML
- VBA Month