Arraylist in 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 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

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

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

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

Содержание

  1. VBA ArrayList
  2. Распространение вашего приложения Excel, содержащего список массивов
  3. Объем объекта списка массивов
  4. Заполнение и чтение из вашего списка массивов
  5. Редактирование и изменение элементов в списке массива
  6. Добавление массива значений в список массивов
  7. Чтение / получение диапазона элементов из списка массива
  8. Поиск элементов в списке массива
  9. Вставка и удаление элементов
  10. Сортировка списка массивов
  11. Клонирование списка массивов
  12. Копирование массива списка в обычный объект массива VBA
  13. Копирование массива списка в диапазон листа
  14. Очистить все элементы из списка массива

VBA ArrayList

Объект ArrayList похож на объект Collection, но имеет гораздо больше методов и свойств и, следовательно, гораздо большую гибкость с точки зрения программирования.

У объекта Collection есть только два метода (Add, Remove) и два свойства (Count, Item), тогда как у Array List их гораздо больше. Кроме того, объект Collection доступен только для чтения. После добавления значений индексированное значение не может быть изменено, тогда как в списке массивов редактирование возможно.

Многие методы Array List используют параметры. В отличие от многих стандартных методов VBA, ни один из этих параметров не является необязательным. Кроме того, некоторые методы и свойства не всегда используют заглавные буквы при вводе так же, как в Excel VBA. Однако они все еще работают.

Размер объекта ArrayList увеличивается и уменьшается в зависимости от количества содержащихся в нем элементов. Перед использованием в качестве массива не требуется определять размеры.

Список массивов является одномерным (таким же, как объект Collection), а тип данных по умолчанию — Variant, что означает, что он принимает данные любого типа, будь то числовые, текстовые или датированные.

Во многих отношениях Array List устраняет ряд недостатков объекта Collection. Он, безусловно, гораздо более гибок в том, что он может делать.

Объект Array List не входит в стандартную библиотеку VBA. Вы можете использовать его в своем коде Excel VBA, используя позднюю или раннюю привязку

1234 Sub LateBindingExample ()Dim MyList As ObjectУстановите MyList = CreateObject («System.Collections.ArrayList»)Конец подписки
123 Sub EarlyBindingExample ()Dim MyList как новый ArrayListКонец подписки

Чтобы использовать пример раннего связывания, вы должны сначала ввести ссылку в VBA на файл «mscorlib.tlb».

Вы делаете это, выбирая «Инструменты | Ссылки ‘из окна редактора Visual Basic (VBE). Появится всплывающее окно со всеми доступными ссылками. Прокрутите вниз до «mscorlib.dll» и установите рядом с ним флажок. Нажмите OK, и эта библиотека теперь является частью вашего проекта:

Одним из больших недостатков объекта Array List является то, что он не имеет «Intellisense». Обычно, когда вы используете объект в VBA, например диапазон, вы увидите всплывающий список всех доступных свойств и методов. Вы не получите этого с объектом Array List, и иногда требуется тщательная проверка, чтобы убедиться, что вы правильно написали метод или свойство.

Кроме того, если вы нажмете F2 в окне VBE и выполните поиск по «arraylist», ничего не будет отображаться, что не очень помогает разработчику.

Ваш код будет работать значительно быстрее с ранним связыванием, потому что он все скомпилирован заранее. При позднем связывании объект должен компилироваться по мере выполнения кода.

Распространение вашего приложения Excel, содержащего список массивов

Как уже указывалось, объект ArrayList не является частью Excel VBA. Это означает, что любой из ваших коллег, которым вы распространяете приложение, должен иметь доступ к файлу «mscorlib.tlb».

Этот файл обычно находится в:

C: Windows Microsoft.NET Framework v4.0.30319

Возможно, стоит написать некоторый код (с использованием метода Dir), чтобы проверить, существует ли этот файл, когда пользователь загружает приложение, чтобы он испытал «мягкую посадку», если он не найден. Если его нет и код запускается, возникнут ошибки.

Кроме того, у пользователя должна быть установлена ​​правильная версия .Net Framework. Даже если у пользователя более поздняя версия, необходимо установить V3.5, иначе ваше приложение не будет работать.

Объем объекта списка массивов

С точки зрения объема объект Array List доступен только при открытой книге. Он не сохраняется при сохранении книги. Если книга открывается повторно, объект Array List необходимо воссоздать с использованием кода VBA.

Если вы хотите, чтобы ваш список массивов был доступен для всего кода в вашем модуле кода, вам необходимо объявить объект списка массивов в разделе «Объявление» в самом верху окна модуля.

Это гарантирует, что весь ваш код в этом модуле сможет получить доступ к списку массивов. Если вы хотите, чтобы какой-либо модуль в вашей книге имел доступ к объекту Array List, определите его как глобальный объект.

1 Глобальная коллекция MyCollection как новый список массивов

Заполнение и чтение из вашего списка массивов

Самое основное действие, которое вы хотите предпринять, — это создать список массивов, поместить в него некоторые данные и затем доказать, что данные можно прочитать. Все примеры кода в этой статье предполагают, что вы используете раннее связывание и добавили «mscorlib.tlb» в ссылки VBA, как описано выше.

123456789101112 Sub ArrayListExample ()‘Создать новый объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в списокMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Просмотрите список массивов, чтобы подтвердить значенияДля N = 0 To MyList.Count — 1MsgBox MyList (N)Следующий NКонец подписки

В этом примере создается новый объект ArrayList, он заполняется 3 элементами и выполняется итерация по списку, отображающему каждый элемент.

Обратите внимание, что индекс ArrayList начинается с 0, а не с 1, поэтому вам нужно вычесть 1 из значения Count.

Вы также можете использовать цикл For… Each для чтения значений:

123456789101112 Sub ArrayListExample ()‘Создать новый объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в списокMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Просмотрите список массивов, чтобы подтвердить значенияДля каждого я в моем спискеMsgBox IДалее яКонец подписки

Редактирование и изменение элементов в списке массива

Основным преимуществом списка массивов перед коллекцией является то, что элементы в списке можно редактировать и изменять в вашем коде. Объект Collection доступен только для чтения, тогда как объект Array List доступен для чтения и записи.

123456789101112131415 Sub ArrayListExample ()‘Создать новый объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в списокMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″«Измените элемент 1 с« Item2 »на« Changed »MyList (1) = «Изменено»«Просмотрите список массивов, чтобы убедиться, что изменение сработало.Для каждого я в моем списке‘Отображаемое название элементаMsgBox IДалее яКонец подписки

В этом примере второй элемент, «Item2», изменяется на значение «Changed» (помните, что индекс начинается с 0). Когда итерация запускается в конце кода, будет отображаться новое значение.

Добавление массива значений в список массивов

Вы можете вводить значения в свой список массивов, используя массив, содержащий список этих значений или ссылки на значения ячеек на листе.

123456789101112131415161718 Sub AddArrayExample ()‘Создать объект списка массивовDim MyList как новый ArrayList‘Перебирать значения массива, добавляя их в список массивовДля каждого v в массиве («A1», «A2», «A3»)‘Добавьте каждое значение массива в списокMyList.Add vСледующий‘Перебирать значения массива со ссылками на листы, добавляя их в список массивовДля каждого v в массиве (Диапазон («A5»). Значение, Диапазон («A6»). Значение)MyList.Add vСледующий‘Просмотрите список массивов, чтобы подтвердить значенияДля N = 0 To MyList.Count — 1‘Показать элемент спискаMsgBox MyList.Item (N)Следующий NКонец подписки

Чтение / получение диапазона элементов из списка массива

Используя метод GetRange в списке массивов, вы можете указать количество последовательных элементов, которые необходимо извлечь. Два обязательных параметра — это начальная позиция индекса и количество элементов, которые нужно получить. Код заполняет второй объект Array List подмножеством элементов, которые затем можно читать отдельно.

123456789101112131415161718 Sub ReadRangeExample ()‘Определите объектыDim MyList как новый ArrayList, MyList1 как объект«Добавить элементы в объект« Мой список »MyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″MyList.Add «Item6″MyList.Add «Item4″MyList.Add «Item7″‘Захватить 4 элемента в« MyList », начиная с позиции индекса 2.Установите MyList1 = MyList.GetRange (2, 4)‘Итерируйте по объекту MyList1, чтобы отобразить подмножество элементовДля каждого я в MyList1‘Отображаемое название элементаMsgBox IДалее яКонец подписки

Поиск элементов в списке массива

Вы можете проверить, есть ли указанный элемент в вашем списке, используя метод «Содержит». Это вернет True или False

1 MsgBox MyList.Contains («Item2»)

Вы также можете узнать фактическую позицию индекса с помощью метода «IndexOf». Вам нужно указать начальный индекс для поиска (обычно 0). Возвращаемое значение — это индекс первого экземпляра найденного элемента. Затем вы можете использовать цикл, чтобы изменить начальную точку на следующее значение индекса, чтобы найти дальнейшие экземпляры, если есть несколько повторяющихся значений.

Если значение не найдено, возвращается значение -1.

Этот пример демонстрирует использование «Содержит», элемент не найден, и цикл по списку массивов, чтобы найти положение всех повторяющихся элементов:

1234567891011121314151617181920212223242526 Sub SearchListExample ()‘Определите список массивов и переменныеDim MyList как новый список ArrayList, Sp как целое число, Pos как целое число‘Добавить новые элементы, включая дубликатMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″MyList.Add «Item1″«Проверить, есть ли элемент 2 в списке» — возвращает значение «Истина».MsgBox MyList.Contains («Item2»)‘Получить индекс несуществующего значения — возвращает -1MsgBox MyList.IndexOf («Элемент», 0)‘Установите начальную позицию для поиска на нольSp = 0«Просмотрите список, чтобы получить все позиции элемента 1».Делать‘Получить позицию индекса следующего« Item1 »на основе позиции в переменной« Sp »Pos = MyList.IndexOf («Item1», Sp)‘Если других экземпляров« Item1 »не найдено, выйдите из цикла.Если Pos = -1, то выйти из Do‘Показать следующий найденный экземпляр и позицию индексаMsgBox MyList (Pos) & «по индексу» & Pos‘Добавьте 1 к последнему найденному значению индекса — теперь это станет новой начальной позицией для следующего поиска.Sp = Pos + 1ПетляКонец подписки

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

Вставка и удаление элементов

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

123456789101112131415 Sub InsertExample ()‘Определить объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в список массиваMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″MyList.Add «Item1″»Вставить» Item6 «в позицию индекса 2MyList.Insert 2, «Item6″‘Перебирайте элементы в списке массивов, чтобы показать новый порядок и позицию индекса.Для N = 0 To MyList.Count — 1MsgBox MyList (N) и «Индекс» и NСледующий NКонец подписки

В этом примере «Item6» добавляется в список в позиции индекса 2, поэтому «item3», который был в позиции индекса 2, теперь перемещается в позицию индекса 3.

Отдельный элемент можно удалить с помощью метода «Удалить».

Обратите внимание, что если имя элемента не найдено, ошибки не возникает. Все последующие порядковые номера будут изменены в соответствии с удалением.

Если вы знаете позицию индекса элемента, вы можете использовать метод «RemoveAt», например.

Обратите внимание, что если указанная позиция индекса больше, чем количество элементов в списке массива, то будет возвращена ошибка.

Вы можете удалить диапазон значений из списка с помощью метода RemoveRange. Параметры — это начальный индекс, а затем количество элементов, которые нужно удалить, например.

1 MyList.RemoveRange 3, 2

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

В обоих методах «RemoveAt» и «RemoveRange» было бы целесообразно использовать некоторый код, чтобы проверить, не превышают ли указанные номера индексов общее количество элементов в списке массивов, чтобы уловить любые возможные ошибки. Свойство «Count» даст общее количество элементов в списке массива.

12345678910111213141516171819202122232425 Sub RemoveExample ()‘Определить объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в список массиваMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″MyList.Add «Item1″MyList.Add «Item4″MyList.Add «Item5″»Вставить» Item6 «в позицию индекса 2MyList.Insert 2, «Item6″‘Remove‘ Item2 ’MyList.Remove «Item2″‘Remove‘ Item ’- этого нет в списке массивов, но не вызывает ошибкуMyList.Remove «Item»‘Удалите элемент из позиции индекса 2MyList.RemoveAt 2‘Удалите 2 последовательных элемента, начиная с позиции индекса 2.MyList.RemoveRange 3, 2‘Просмотрите список массивов, чтобы показать, что осталось, и в какой позиции индекса он сейчас находится.Для N = 0 To MyList.Count — 1MsgBox MyList (N) и «Индекс» и NСледующий NКонец подписки

Обратите внимание: если вы используете «RemoveAt» для удаления элемента в определенной позиции, то, как только этот элемент будет удален, все последующие позиции индекса изменятся. Если у вас есть несколько удалений с использованием позиции индекса, то хорошей идеей будет начать с самого высокого номера индекса и сделать шаг назад до нулевой позиции, чтобы вы всегда удаляли правильный элемент. Таким образом, у вас не будет проблем

Сортировка списка массивов

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

Объект Array List — единственный объект в Excel VBA с методом сортировки. Метод сортировки очень быстрый, и это может быть важным соображением при использовании списка массивов.

В объекте коллекции требовалось некоторое нестандартное мышление, чтобы отсортировать все элементы, но со списком массивов это очень просто.

Метод «Сортировка» выполняет сортировку по возрастанию, а метод «Обратный» — по убыванию.

12345678910111213141516171819202122 Sub ArrayListExample ()‘Создать объект списка массивовDim MyList как новый ArrayList‘Добавить товары в несортированном порядкеMyList.Add «Item1″MyList.Add «Item3″MyList.Add «Item2″‘Сортировка товаров в порядке возрастанияMyList.Sort‘Перебирайте элементы, чтобы отображать их в порядке возрастания.Для каждого я в моем списке‘Отображаемое название элементаMsgBox IДалее я‘Сортировка товаров в порядке убыванияMyList.Reverse‘Перебирайте элементы, чтобы отображать их в порядке убыванияДля каждого я в моем списке‘Отображаемое название элементаMsgBox IДалее яКонец подписки

Клонирование списка массивов

Список массивов имеет возможность создать клон или копию самого себя. Это полезно, если пользователь вносит изменения в элементы с помощью внешнего интерфейса и вашего кода VBA, но вам нужно сохранить копию элементов в их исходном состоянии в качестве резервной копии.

Это может предоставить пользователю функцию «Отменить». Возможно, они внесли изменения и захотят вернуться к исходному списку.

123456789101112131415 Sub CloneExample ()‘Определите два объекта — список массивов и объектDim MyList как новый ArrayList, MyList1 как объект‘Заполните первый объект элементамиMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Скопируйте MyList в MyList1Установите MyList1 = MyList.Clone‘Просмотрите MyList1, чтобы доказать клонированиеДля каждого я в MyList1‘Отображаемое название элементаMsgBox IДалее яКонец подписки

«MyList1» теперь содержит все элементы из «MyList» в том же порядке.

Копирование массива списка в обычный объект массива VBA

Вы можете использовать простой метод для копирования списка массивов в обычный массив VBA:

123456789101112131415 Sub ArrayExample ()‘Создайте объект списка массивов и стандартный объект массиваDim MyList как новый ArrayList, NewArray как вариант‘Заполните список массива элементамиMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Скопируйте список массивов в новый массивNewArray = MyList.ToArray‘Итерируйте по новому массиву — обратите внимание, что счетчик списка массивов обеспечивает максимальный индексДля N = 0 To MyList.Count — 1‘Отображаемое название элементаMsgBox NewArray (N)Следующий NКонец подписки

Копирование массива списка в диапазон листа

Вы можете скопировать свой список массивов на конкретный рабочий лист и ссылку на ячейку без необходимости перебирать список массивов. Вам нужно только указать первую ссылку на ячейку

123456789101112131415 Sub RangeExample ()‘Создать новый объект списка массивовDim MyList как новый ArrayList‘Добавить элементы в списокMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Очистить целевой листЛисты («Лист1»). UsedRange.Clear‘Копировать элементы в строкеЛисты («Sheet1»). Диапазон («A1»). Resize (1, MyList.Count) .Value = MyList.toArray‘Копировать элементы вниз по столбцуЛисты («Sheet1»). Range («A5»). Resize (MyList.Count, 1) .Value = _WorksheetFunction.Transpose (MyList.toArray)Конец подписки

Очистить все элементы из списка массива

Существует простая функция (Очистить) для полной очистки списка массивов.

1234567891011121314 Sub ClearListExample ()‘Создать объект списка массивовDim MyList как новый ArrayList‘Добавить новые товарыMyList.Add «Item1″MyList.Add «Item2″MyList.Add «Item3″‘Показать количество товаровMsgBox MyList.Count‘Очистить все элементыMyList.Clear‘Покажите количество предметов, чтобы доказать, что очистка сработалаMsgBox MyList.CountКонец подписки

В этом примере создаются элементы в списке массивов, а затем этот список очищается. Окна сообщений подтверждаются до и после количества элементов в списке массива.

Источник

An ArrayList is a data structure which uses an underlying array with extra capacity and a size variable which keeps track of the number of items in the array. The purpose of the ArrayList is to make adding elements to an array more efficient. Whenever the size of the ArrayList reaches to capacity of the underlying array, the array is reallocated with double its capacity to allow space for additional elements to be added. There is no built-in ArrayList class in VBA. The .NET ArrayList class can be used by installing .NET version 3.5 and setting a reference to mscorlib.tlb. Alternatively, an ArrayList class can be implemented using VBA.

.NET ArrayList

To access the .NET ArrayList class, Microsoft .NET Framework 3.5 must be installed on the user’s computer. A reference can then be set to the mscorlib library. No intellisense is available for the mscorlib ArrayList and the Object Browser has limited information about the classes in mscorlib. If run-time error -2146232576 (80131700) occurs when trying to instantiate an ArrayList it is because the correct version of the .NET framework is not installed.

ArrayList Automation Error

Public Sub Example()

    'Set reference to mscorlib.tlb
    Dim A As ArrayList
    Set A = New ArrayList

End Sub

Public Sub Example()

    'Late-binding
    Dim A As Object
    Set A = CreateObject("System.Collections.ArrayList")

End Sub

VBA Implementation

An ArrayList can be implemented using VBA in a variety of ways. Specific implementations can be used to handle specific data types and provide different functionality. ArrayList implementations include:

  • clsArrayListVariant (Value types only)
  • clsArrayListString
  • clsArrayListObject
  • clsArrayListUDT

Download an implementation from GitHub and import the module into a VBA project.

Public Sub Example()

    Dim AL As clsArrayListString
    Set AL = New clsArrayListString
    
    AL.Append "A"
    AL.Append "B"
    AL.Append "C"
    AL.Append "D"
    AL.Append "E"
    AL.Append "F"
    AL.Append "G"

    AL.Reverse
    Debug.Print AL.JoinString(",")

    AL.Sort
    Debug.Print AL.JoinString(",")
    
End Sub

If you are coding professionally in VBA, most probably you are using arrays every now and then and you have your own function for sorting an array.

Something like this bubble sort or anything similar is what you have written at least once in your code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

Public Function fnVarBubbleSort(ByRef varTempArray As Variant) As Variant

    Dim varTemp                 As Variant

    Dim lngCounter              As Long

    Dim blnNoExchanges          As Boolean

    Do

        blnNoExchanges = True

        For lngCounter = LBound(varTempArray) To UBound(varTempArray) 1

            If CDbl(varTempArray(lngCounter)) > CDbl(varTempArray(lngCounter + 1)) Then

                blnNoExchanges = False

                varTemp = varTempArray(lngCounter)

                varTempArray(lngCounter) = varTempArray(lngCounter + 1)

                varTempArray(lngCounter + 1) = varTemp

            End If

        Next lngCounter

    Loop While Not (blnNoExchanges)

    fnVarBubbleSort = varTempArray

   On Error GoTo 0

   Exit Function

End Function

And while writing it you were thinking something like – why am I not coding in C#, Java, C++, Python etc? 🙂

Well, to be honest, the bubble sort above was used by me as well. Until lately, when I have actually decided to use ArrayList for sorting of arrays, instead of using the good old bubble sort.

Thus, something like this is always handy:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Option Explicit

Public Sub TestMe()

    Dim arrList     As Object

    Set arrList = CreateObject(«System.Collections.ArrayList»)

    Dim someArray   As Variant

    someArray = Array(3, 4, 0, 1, 2, 33, 5, 4)

    Dim cnt As Long

    For cnt = LBound(someArray) To UBound(someArray)

        arrList.Add someArray(cnt)

    Next cnt

    arrList.Sort

    ReDim someArray(arrList.Count)

    For cnt = 0 To arrList.Count 1

        arrList(cnt) = arrList.Item(cnt)

        Debug.Print arrList(cnt)

    Next cnt

End Sub

And here is the result in the immediate window:

Enjoy it (either the code above or Kylie).

Понравилась статья? Поделить с друзьями:
  • Arrayformula excel на русском
  • Array vba excel примеры
  • Array vba excel описание
  • Array to excel phpexcel
  • Array of arrays in excel vba