List array vba excel

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:

  1. Select Tools and then References from the menu.
  2. Click on the Browse.
  3. Find the file mscorlib.tlb and click Open. It should be in a folder like this C:WindowsMicrosoft.NETFrameworkv4.0.30319.
  4. Scroll down the list and check mscorlib.dll.
  5. 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 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:

Pic 01

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!

automacro

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

Уровень сложности
Простой

Время на прочтение
5 мин

Количество просмотров 3.4K

Когда я впервые встретил этот класс, подумал «Зачем? Ведь есть простые массивы». А потом попробовал и не представляю как жил без него раньше.

Начну сразу с примера

Предположим, на активном листе в столбце 1 находится список ФИО сотрудников.

Список ФИО

Список ФИО

Наша задача собрать в массив только уникальные ФИО и отсортировать его по убыванию (ну такая вот немного странная задача). Сначала решим ее без использования ArrayList, а в конце сравним результат.

Для получения уникальных значений, создаем функцию GetDistinctItems и в нее передаем столбец с ФИО. В самой функции пробегаем циклом For Each по всем ФИО и добавляем уникальные в объект Buffer (Dictionary). Далее методом Keys извлекаем элементы в дополнительную функцию DescendingSort (используем сортировку пузырьком) и получаем отсортированные значения в переменную Sorted, которую и возвращаем как результат функции.

Public Sub Main()
    Dim FullNameColumn As Range
    Set FullNameColumn = ActiveSheet.UsedRange.Columns(1) ' Получаем первый столбец.

    Dim DistinctList As Variant
    DistinctList = GetDistinctItems(FullNameColumn) ' Передаем диапазон в функцию.
    Debug.Print Join(DistinctList, vbCrLf) ' Выводим результат.
End Sub

Public Function GetDistinctItems(ByRef Range As Range) As Variant
    Dim Data As Variant: Data = Range.Value ' Преобразуем диапазон в массив.
    Dim Buffer As Object: Set Buffer = CreateObject("Scripting.Dictionary") ' Создаем объект Dictionary.

    Dim Item
    For Each Item In Data
        If Not Buffer.Exists(Item) Then Buffer.Add Item, Empty ' Проверяем наличие элемента и добавляем если отсутствует.
    Next
    
    Dim Sorted As Variant
    Sorted = DescendingSort(Buffer.Keys()) ' Сортируем функцией DescendingSort.
    GetDistinctItems = Sorted ' Возвращаем результат.
End Function

Public Function DescendingSort(ByRef Data As Variant) As Variant
    Dim i As Long
    For i = LBound(Data) To UBound(Data) - 1
        Dim j As Long
        For j = i + 1 To UBound(Data)
            If Data(i) < Data(j) Then
                Dim Temp As Variant
                Temp = Data(j)
                Data(j) = Data(i)
                Data(i) = Temp
            End If
        Next
    Next

    DescendingSort = Data
End Function

Результат

Результат

Тривиально? Вполне. Компактно? Ну в целом да, но в конце мы напишем еще более компактней, а заодно решим проблему написания новой функции, если вдруг результат нужно будет сортировать по возрастанию.

Что есть такое

Начнем с того, что ArrayList это класс из пространства имен System.Collections библиотеки mscorlib, который реализует интерфейс IList. Естественно, в VBA он несколько порезан в плане методов, иначе и быть не могло (например нет методов AddRange или BinarySearch). Но и тем не менее с ним можно (и нужно) работать.
По сути, это динамический массив. Его не нужно самостоятельно переопределять, чтобы изменить размерность, достаточно добавлять элементы с помощью метода Add. Где-то я читал, что на низком уровне (да простят меня знатоки, я не знаю правильно ли я применяю это словосочетание здесь) есть свои нюансы в плане производительности, но, откровенно говоря, за все время использования этого объекта каких-либо проблем я не замечал и время работы макроса из-за него если и растет вообще, то совсем не критично.

В чем же сила брат удобство?

Как минимум в том, что это динамический массив. Вы просто добавляете элементы через метод и не нужно заморачиваться на тему ReDim (и уж тем более Preserve) и вычислений размеров будущего массива.

А дальше начинаются вкусняхи

Во-первых, мы можем выгрузить все элементы одним методом ToArray. Как следует из названия, он преобразует все элементы объекта в обычный массив типа Variant.
Во-вторых, мы можем составлять список уникальных значений, проверяя их наличие методом Contains.

В-третьих, можно забыть про функцию UBound, ведь у этого класса есть свойство Count, которое, как не сложно догадаться, возвращает количество элементов помещенных в объект.
В-четвертых, есть возможность быстро отсортировать элементы как по возрастанию (метод Sort), так и по убыванию (сначала используем метод Sort, а после метод Reverse).

Ну и быстро пробегаем по оставшимся свойствам:

Item(Index)
Предоставляет доступ к элементу по его индексу.

и методам:

IndexOf(Item, StartFrom)
Возвращает индекс элемента. Обязательный аргумент StartFrom поможет найти каждый последующий индекс одинаковых элементов.

RemoveAt(Index)
Удаляет элемент по индексу.

Remove(Item)
Удаляет переданный элемент.

RemoveRange(StartPosition, Count)
Удаляет диапазон элементов. StartPosition указывает на индекс первого элемента, Count на количество элементов в удаляемом диапазоне.

Clear()
Удаляет все элементы.

Insert(Position, Item)
Добавляет элемент по заданной позиции.

Clone()
Создает копию объекта (по сути создает новый объект, а не возвращает ссылку на текущий).

Как создать это чудо

Создать объект класса ArrayList можно с помощью функции CreateObject:

Dim List As Object
Set List = CreateObject("System.Collections.ArrayList")

или через Tools -> Reference подключить библиотеку mscorlib.dll, а дальше создавать как обычный объект:

Dim List As New ArrayList

Минус и той и другой привязки в том, что интерфейс объекта вы не получите. Причину лично я не знаю, но почему-то VBA в Excel (больше нигде не проверял) не видит свойства и методы этого класса (в поздней привязке их и так нет ни у какого объекта, так как тип переменной Object, а вот в ранней обычно есть).

Можно, конечно, получить часть интерфейса, объявив переменную с типом IList и уже после этого присвоить ей инстанс ArrayList, но тем самым мы потеряем бОльшую часть функционала, например методы Sort, ToArray, Reverse.

Вернемся в начало

Помните наш пример? Предлагаю решение с новыми знаниями.

Теперь мы добавляем уникальные значения в объект Buffer (ArrayList), перед этим проверяя методом Contains наличие ФИО в списке элементов. По окончанию цикла применяем метод Sort и Reverse для получения списка по убыванию. Выгружаем результат методом ToArray. Согласитесь на этот раз все гораздо компактней.

Public Sub Main()
    Dim FullNameColumn As Range
    Set FullNameColumn = ActiveSheet.UsedRange.Columns(1) ' Получаем первый столбец.

    Dim DistinctList As Variant
    DistinctList = GetDistinctItems(FullNameColumn) ' Передаем диапазон в функцию.
    Debug.Print Join(DistinctList, vbCrLf) ' Выводим результат.
End Sub

Public Function GetDistinctItems(ByRef Range As Range) As Variant
    Dim Data As Variant: Data = Range.Value ' Преобразуем диапазон в массив.
    Dim Buffer As Object: Set Buffer = CreateObject("System.Collections.ArrayList") ' Создаем объект ArrayList.

    Dim Item
    For Each Item In Data
        If Not Buffer.Contains(Item) Then Buffer.Add Item ' Проверяем наличие элемента и добавляем если отсутствует.
    Next

    Buffer.Sort: Buffer.Reverse ' Сортируем по возрастанию, а потом переворачиваем (по убыванию).
    GetDistinctItems = Buffer.ToArray() ' Выгружаем в виде массива.
End Function

Итоговый результат

Итоговый результат

Что в итоге

В итоге мы имеем преимущество перед классом Collection в том, что есть проверка на наличие элемента в списке (без танцев с бубном) и быстрая выгрузка в виде массива (без написания цикла).

Перед классом Dictionary, пожалуй, преимущество в отсутствии необходимости прописывать ключи (если они изначально не нужны).

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

В общем и целом, достаточно удобный в применении класс для работы с одномерными массивами. Конечно, получать данные из объекта Range гораздо проще в обычный массив, но если нужно создавать новый (например в цикле), то, как по мне, ArrayList превосходный вариант.

P.S. (проблемки, проблемушки)

Уже после написания статьи обратил внимание, что мой пример на чистом ПК не работает, появляется automation error -2146232576 при создании объекта ArrayList.

Судя по этому ответу, для работы mscorlib необходимо включить .NET Framework 3.5.

Сделать это можно через Панель управления -> Программы -> Включение или отключение компонентов Windows -> поставить галочку напротив .NET Framework 3.5 (включает .NET 2.0 и 3.0) после чего на ПК скачаются необходимые файлы для работы компонента.

Обязательно после проделанных действий перезагрузить Excel. У меня при установке выдал ошибку. Исправилось выключением Excel и повторным включением компонента.

К слову на моем рабочем ПК таких проблем не было, т.е. данный компонент уже был подключен организацией (или по умолчанию в ранних Windows, не знаю точно).

Спасибо, что прочитали до конца.

Как насчет применения этого класса? Пишите в комментариях!
А также, подписывайтесь на мой 
телеграмм.

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

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.

  1. Go to “Tools” > “References.”

    Reference step 1

  2. Object library reference window will appear in front of you. Select the option “mscorlib.dll.”
  3. Click on “OK.” Now, we can access the VBA ArrayList.

    Reference step 2

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

VBA ArrayList Example 1

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

VBA ArrayList Example 1-1

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

VBA ArrayList Example 1-2

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

Example 1-3

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.

VBA ArrayList Example 1-4

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

Example 2

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.

Example 2-1

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.

VBA ArrayList Example 2-2

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

VBA ArrayList

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.

VBA ArrayList Example 1-1

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

VBA ArrayList Example 1-2

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

VBA ArrayList Example 1-3

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

VBA ArrayList Example 1-4

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

VBA ArrayList Example 1-5

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

VBA ArrayList Example 1-6

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

VBA ArrayList Example 1-7

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

VBA ArrayList Example 1-8

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.

Result of Example 1-9

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’

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

VBA ArrayList Example 2-1

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

VBA ArrayList Example 2-2

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

VBA ArrayList Example 2-3

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

VBA ArrayList Example 2-4

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

VBA ArrayList Example 2-5

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.

Result of Example 2-6

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

VBA ArrayList Example 2-7

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.

Result of Example 2-8

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

ArraySort.Reverse Example 3-1

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.

Result of Example 3-2

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 –

  1. VBA Arrays
  2. VBA Sort
  3. VBA XML
  4. VBA Month

The VBA ArrayList is also a very useful data structure if you want to work with dynamic VBA arrays but don’t want the hassle of having to constantly redefine (Redim) the size of the array. ArrayLists don’t have a fixed size so you can keep adding items to it. However, in VBA in can be better superseded by the Native VBA Collection.

VBA ArrayList example

Below is an example of creating a VBA ArrayList and adding an item:

Dim arrList as Object
Set arrList = CreateObject("System.Collections.ArrayList") 'Create the ArrayList

arrList.Add "Hello" 'Adding items to an ArrayList
arrList.Add "You"
arrList.Add "There"
arrList.Add "Man"

'Get number of items
Debug.Print arrList.Count 'Result: 3 

For Each item In arrList
  Debug.Print item
Next Item
'Result: Hello, You, There, Man

Removing items

You can remove all items of a particular value from a VBA ArrayList by using Remove:

Dim arrList as Object
Set arrList = CreateObject("System.Collections.ArrayList") 'Create the ArrayList

arrList.Add "Hello"  'Add "Hello"
arrList.Add "You"    'Add "You"
arrList.Remove "You" 'Remove "You"

For Each item In arrList
  Debug.Print item
Next Item
'Result: Hello

To remove items at a particular index use RemoveAt instead. Remember that indexing starts at 0.

Dim arrList as Object
Set arrList = CreateObject("System.Collections.ArrayList") 'Create the ArrayList

arrList.Add "Hello"  'Add "Hello"
arrList.Add "You"    'Add "You"
arrList.Add "There"    'Add "There"
arrList.RemoveAt (0)

For Each item In arrList
  Debug.Print item
Next Item
'Result: You, There

Get and Count items

To get an item at a particular index using the Item property. Remember that indexing in the VBA ArrayList starts at 0.

To count the number of items in the VBA ArrayList simply use the Count property:

Dim arrList as Object
Set arrList = CreateObject("System.Collections.ArrayList") 'Create the ArrayList

arrList.Add "Hello"  'Add "Hello"
arrList.Add "You"    'Add "You"

Debug.Print arrList.Count 'Result: 2

Debug.Print arrList.Item(1) 'Result: You

Clear items

To clear a VBA ArrayList simply use Clear:

Dim arrList as Object
Set arrList = CreateObject("System.Collections.ArrayList") 'Create the ArrayList

arrList.Add "Hello"  'Add "Hello"
arrList.Add "You"    'Add "You"

arrList.Clear

Debug.Print arrList.Count 'Result: 0

On a regular basis use rather the VBA Collection instead of the VBA ArrayList

Содержание

  1. VBA ArrayList
  2. Excel VBA ArrayList
  3. Examples of VBA ArrayList in Excel
  4. Example #1 – Create Instance of VBA ArrayList
  5. Example #2 – Store Values to Cells Using VBA ArrayList
  6. Recommended Articles
  7. VBA ArrayList – Mega-Guide Updated for 2022
  8. Using a VBA ArrayList
  9. Distributing Your Excel Application Containing an Array List
  10. Scope of an Array List Object
  11. Populating and Reading from Your Array List
  12. Editing and Changing Items in an Array List
  13. VBA Coding Made Easy
  14. Adding an Array of Values to an Array List
  15. Reading / Retrieving a Range of Items from an Array List
  16. Searching for Items Within an Array List
  17. Insert and Remove Items
  18. Sorting an Array List
  19. Cloning an Array List
  20. Copying a List Array into a Conventional VBA Array Object
  21. Copying a List Array into a Worksheet Range
  22. Empty All Items from an Array List
  23. Array List Methods Summary for Excel VBA
  24. VBA Code Examples Add-in

VBA ArrayList

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

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.

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.

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.

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:

Step 2: Since the ArrayList is an object, we need to create a new instance.

Code:

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:

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.

Let’s show this in the message box.

Code:

Like this, we can store any number of values with an Array List Object.

Example #2 – Store Values to Cells Using VBA ArrayList

Code:

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:

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: –

Источник

VBA ArrayList – Mega-Guide Updated for 2022

In this Article

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.

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:

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.

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.

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:

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.

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!

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

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.

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

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:

Note that the search text used is case sensitive and wild cards are not accepted.

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.

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.

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.

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.

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.

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.

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.

‘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:

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

Empty All Items from an Array List

There is a simple function (Clear) to clear the array list completely

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

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

I want to have an array list in vba, hence I have a variant declared in excel vba like:

Dim Students(10) as variant

Now I want to store numbers in Students list. the numbers are not continuous. Sometime like:

Students(2,7,14,54,33,45,55,59,62,66,69)

How can I do this in vba? also how can I access the list items?

Community's user avatar

asked Jan 26, 2012 at 19:15

user793468's user avatar

user793468user793468

4,87823 gold badges80 silver badges126 bronze badges

Students must be declared as a dynamic array. That is, an array whose bounds can be changed. Dim Students(10) gives an array whose bounds cannot be changed and cannot be loaded from an array.

Dim Students() As Variant

To load Students:

Students = Array(2,7,14,54,33,45,55,59,62,66,69)

To access the elements:

Dim Inx As Long

For Inx = LBound(Students) to UBound(Students)
  Debug.Print Students(Inx)
Next

LBound (Lower bound) and UBound mean that the for loop adjusts to the actual number of elements in Students.

answered Jan 26, 2012 at 19:30

Tony Dallimore's user avatar

Tony DallimoreTony Dallimore

12.3k7 gold badges31 silver badges61 bronze badges

2

This is too complex for you right now, and you’ll probably never run into a situation where you’ll need this, but:

I use the following method for forming more memory-efficient arrays (because Variant uses the most memory of any variable type) while still having the convenience of declaring the array contents in one line. To follow your example:

Dim Students() As Long
Dim Array2() As String

Array2() = Split("2,7,14,54,33,45,55,59,62,66,69", ",")

ReDim Array1(0) As Long
For Loop1 = LBound(Array2()) To UBound(Array2())
    ReDim Preserve Array1(0 To (UBound(Array1) + 1)) As String
    Array1(Loop1) = Array2(Loop1)
Next Loop1
ReDim Preserve Array1(0 To (UBound(Array1) - 1)) As Long

Erase Array2

An example of accessing it would be something like:

For Loop1 = LBound(Students) to UBound(Students)
    Msgbox Students(Loop1)
Next Loop1

I learned this from here: http://www.vbforums.com/showthread.php?669265-RESOLVED-VBA-Excel-Assigning-values-to-array-in-a-single-line&p=4116778&viewfull=1#post4116778

answered May 21, 2015 at 21:58

puzzlepiece87's user avatar

puzzlepiece87puzzlepiece87

1,5172 gold badges19 silver badges34 bronze badges

2

You can add values to an Array like this…

For i = 1 to 10
    Students(i) = i
Next i

Or like this

Students = Array(2,7,14,54,33,45,55,59,62,66,69)

Then you can access the values in the same manor. Note if you use the second option you’ll need to declare it as follows:

Dim Students() As Variant

answered Jan 26, 2012 at 19:24

Skytunnel's user avatar

Well,
That depends on how you would supply the values for the array, would you get the values from Worksheet.Range or from TextBox or ListBox , But basically the code would be something like that :

Dim students(10) as Integer
Dim Carrier as Integer
For i = LBound(students) To UBound(Students)
     'some code to get the values you want to from whatever is your source
     'then assign the value to Carrier

     students(i)=Carrier
Next i

It is not good practice to dim an array as Variant when you certainly know that you are going to use integers only, as it will eat alot of memory that is not needed in the first place.
You also should be aware of the bounds of the numbers that are going to be assigned, if it exceeds the Integer limit then you should use Double or Float.
This is my first participation in the site,Cheers.

answered Aug 30, 2015 at 21:39

Mohammed Ehsan's user avatar

Like this post? Please share to your friends:
  • List of two word animals
  • List all word processors
  • List all word classes
  • List of three word phrases
  • List all objects excel vba