Excel vba массивы списки

Массивы в VBA Excel: одномерные, многомерные и динамические. Объявление и использование массивов. Операторы Public, Dim и ReDim. Функции Array, LBound, UBound.

Массивы – это множества однотипных элементов, имеющих одно имя и отличающиеся друг от друга индексами. Они могут быть одномерными (линейными), многомерными и динамическими. Массивы в VBA Excel, как и другие переменные, объявляются с помощью операторов Dim и Public. Для изменения размерности динамических массивов используется оператор ReDim. Массивы с заранее объявленной размерностью называют статическими.

Одномерные массивы

Объявление одномерных (линейных) статических массивов в VBA Excel:

Public Massiv1(9) As Integer

Dim Massiv2(1 To 9) As String

В первом случае публичный массив содержит 10 элементов от 0 до 9 (нижний индекс по умолчанию — 0, верхний индекс — 9), а во втором случае локальный массив содержит 9 элементов от 1 до 9.

По умолчанию VBA Excel считает в массивах нижним индексом нуль, но, при желании, можно сделать нижним индексом по умолчанию единицу, добавив в самом начале модуля объявление «Option Base 1».

Многомерные массивы

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

‘Массив двухмерный

Public Massiv1(3, 6) As Integer

‘Массив трехмерный

Dim Massiv2(1 To 6, 1 To 8, 1 To 5) As String

‘Массив четырехмерный

Dim Massiv3(9, 9, 9, 9) As Date

Третий массив состоит из 10000 элементов — 10×10×10×10.

Динамические массивы

Динамические массивы в VBA Excel, в отличие от статических, объявляются без указания размерности:

Public Massiv1() As Integer

Dim Massiv2() As String

Такие массивы используются, когда заранее неизвестна размерность, которая определяется в процессе выполнения программы. Когда нужная размерность массива становится известна, она в VBA Excel переопределяется с помощью оператора ReDim:

Public Massiv1() As Integer

Dim Massiv2() As String

ReDim Massiv1(1 To 20)

ReDim Massiv2(3, 5, 4)

При переопределении размерности массива вместо верхнего индекса можно использовать переменную:

Dim Massiv1() as Variant, x As Integer

x = 20

ReDim Massiv1(1 To x)

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

С помощью оператора ReDim невозможно изменить обычный массив, объявленный с заранее заданной размерностью. Попытка переопределить размерность такого массива вызовет ошибку компиляции с сообщением: Array already dimensioned (Массив уже измерен).

При переопределении размерности динамических массивов в VBA Excel теряются значения их элементов. Чтобы сохранить значения, используйте оператор Preserve:

Dim Massiv1() As String

операторы

ReDim Massiv1(5, 2, 3)

операторы

ReDim Preserve Massiv1(5, 2, 7)

Обратите внимание!
Переопределить с оператором Preserve можно только последнюю размерность динамического массива. Это недоработка разработчиков, которая сохранилась и в VBA Excel 2016. Без оператора Preserve можно переопределить все размерности.

Максимальный размер

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

По информации с сайта разработчиков, максимальный размер массивов зависит от операционной системы и доступного объема памяти. Использование массивов, размер которых превышает объем доступной оперативной памяти компьютера, приводит к снижению скорости, поскольку системе необходимо выполнять запись данных и чтение с диска.

Использование массивов

Приведу два примера, где не обойтись без массивов.

1. Как известно, функция Split возвращает одномерный массив подстрок, извлеченных из первоначальной строки с разделителями. Эти данные присваиваются заранее объявленному строковому (As String) одномерному динамическому массиву. Размерность устанавливается автоматически в зависимости от количества подстрок.

2. Данные в массивах обрабатываются значительно быстрее, чем в ячейках рабочего листа. Построчную обработку информации в таблице Excel можно наблюдать визуально по мерцаниям экрана, если его обновление (Application.ScreenUpdating) не отключено. Чтобы ускорить работу кода, можно значения из диапазона ячеек предварительно загрузить в динамический массив с помощью оператора присваивания (=). Размерность массива установится автоматически. После обработки данных в массиве кодом VBA полученные результаты выгружаются обратно на рабочий лист Excel. Обратите внимание, что загрузить значения в диапазон ячеек рабочего листа через оператор присваивания (=) можно только из двумерного массива.

Функции Array, LBound, UBound

Функция Array

Функция Array возвращает массив элементов типа Variant из первоначального списка элементов, перечисленных через запятую. Нумерация элементов в массиве начинается с нуля. Обратиться к элементу массива можно, указав в скобках его номер (индекс).

Sub Test1()

Dim a() As Variant

a = Array(«text», 25, «solo», 35.62, «stop»)

MsgBox a(0) & vbNewLine & a(1) & vbNewLine _

& a(2) & vbNewLine & a(3) & vbNewLine & a(4)

End Sub

Скопируйте код в модуль VBA Excel и запустите его на выполнение. Информационное сообщение MsgBox покажет значения массива, извлеченные по индексу.

Функция LBound

Функция LBound возвращает значение типа Long, равное наименьшему (нижнему) доступному индексу в указанном измерении массива.
Синтаксис:
LBound (arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Наименьший индекс по-умолчанию может быть равен 0 или 1 в зависимости от настроек оператора Option Base. Нижняя граница архива, полученного с помощью функции Array, всегда равна 0.

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

Функция UBound

Функция UBound возвращает значение типа Long, равное наибольшему (верхнему) доступному индексу в указанном измерении массива.
Синтаксис:
UBound( arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Функция UBound используется вместе с функцией LBound для определения размера массива.

Sub Test2()

Dim a(2 To 53) As String

MsgBox «Наименьший индекс = « & LBound(a) & _

vbNewLine & «Наибольший индекс = « & UBound(a)

End Sub

Скопируйте код в модуль VBA Excel и запустите его на выполнение. Информационное сообщение MsgBox покажет значения наименьшего и наибольшего индекса переменной массива a.

Обход массива циклом

Обход одномерного массива циклом For… Next, в котором для определения границ массива используются функции UBound и LBound:

Sub Test3()

Dim a() As Variant, i As Long

a = Array(«text», 25, «solo», 35.62, «stop»)

    For i = LBound(a) To UBound(a)

        Debug.Print «a(« & i & «) = « & a(i)

    Next

End Sub

Результат работы цикла вы увидите в окне Immediate.

Очистка (обнуление) массивов

Первый способ

Очистить любой массив, статический или динамический, без использования цикла можно с помощью оператора Erase. Термин «обнуление» можно применить только к массиву числового типа.

Dim Massiv1(4, 3) As String,  Massiv2() As Variant

операторы

‘переопределяем динамический массив

ReDim Massiv2(2, 5, 3)

операторы

‘очищаем массивы

Erase Massiv1

Erase Massiv2

Обратите внимание, что оба массива при таком способе очистки будут возвращены в исходное состояние, которое они имели сразу после объявления:

  • статический Massiv1 сохранит размерность (4, 3);
  • динамический Massiv2 не сохранит размерность ().

Второй способ

Динамический массив можно очистить (обнулить) без использования цикла с помощью оператора ReDim. Просто переопределите его с той же размерностью.

Dim Massiv() As Double

операторы

‘переопределяем массив

ReDim Massiv(5, 6, 8)

операторы

‘очищаем массив

ReDim Massiv(5, 6, 8)


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

На чтение 24 мин. Просмотров 90.5k.

VBA Arrays

Дональд Кнут

Список настолько же силен, как и его самое слабое звено

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

Содержание

  1. Краткое руководство по массивам VBA
  2. Введение
  3. Быстрые заметки
  4. Что такое массивы и зачем они нужны?
  5. Типы массивов VBA
  6. Объявление массива
  7. Присвоение значений массиву
  8. Использование функций Array и Split
  9. Использование циклов с массивами
  10. Использование Erase
  11. ReDim с Preserve
  12. Сортировка массива
  13. Передача массива в Sub или функцию
  14. Возвращение массива из функции
  15. Двумерные массивы
  16. Чтение из диапазона ячеек в массив
  17. Как заставить ваши макросы работать на суперскорости
  18. Заключение

Краткое руководство по массивам VBA

Задача Статический
массив
Динамический
массив
Объявление Dim arr(0 To 5) As
Long
Dim arr() As Long
Dim arr As Variant
Установить размер Dim arr(0 To 5) As
Long
ReDim arr(0 To 5)As
Variant
Увеличить размер
(сохранить
существующие
данные)
Только
динамический
ReDim Preserve arr(0 To 6)
Установить
значения
arr(1) = 22 arr(1) = 22
Получить значения total = arr(1) total = arr(1)
Первая позиция LBound(arr) LBound(arr)
Последняя позиция Ubound(arr) Ubound(arr)
Читать все записи (1D) For i = LBound(arr) To UBound(arr)
Next i
Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
For i = LBound(arr) To UBound(arr)
Next i
Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
Читать все записи (2D) For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
Читать все записи Dim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Перейти на Sub Sub MySub(ByRef arr() As String) Sub MySub(ByRef arr() As String)
Возврат из функции Function GetArray() 
As Long()
    Dim arr(0 To 5) As
Long
    GetArray = arr
End Function
Function GetArray() 
As Long()
    Dim arr() As Long
    GetArray = arr
End Function
Получить от
функции
Только
динамический
Dim arr() As Long 
Arr = GetArray()
Стереть массив Erase arr
*Сбрасывает все
значения по
умолчанию
Erase arr
*Удаляет массив
Строка в массив Только
динамический
Dim arr As Variant
arr = Split(«James:Earl:Jones»,»:»)
Массив в строку Dim sName As String
sName = Join(arr, «:»)
Dim sName As String
sName = Join(arr, «:»)
Заполните
значениями
Только
динамический
Dim arr As Variant
arr = Array(«John», «Hazel», «Fred»)
Диапазон в массив Только
динамический
Dim arr As Variant
arr = Range(«A1:D2»)
Массив в диапазон Так же, как в
динамическом
Dim arr As Variant
Range(«A5:D6») = arr

Введение

В этой статье подробно рассматриваются массивы на языке программирования Excel VBA. Она охватывает важные моменты, такие как:

  • Зачем вам массивы
  • Когда вы должны их использовать
  • Два типа массивов
  • Использование более одного измерения
  • Объявление массивов
  • Добавление значений
  • Просмотр всех предметов
  • Супер эффективный способ чтения Range в массив

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

Быстрые заметки

Иногда коллекции лучше, чем массивы. Вы можете прочитать о коллекциях здесь.

Массивы и циклы идут рука об руку. Наиболее распространенными циклами, которые вы используете с массивами, являются циклы For i и For Each.

Что такое массивы и зачем они нужны?

Массив VBA — это тип переменной. Используется для хранения списков данных одного типа. Примером может быть сохранение списка стран или списка итогов за неделю.

В VBA обычная переменная может хранить только одно значение за раз.

В следующем примере показана переменная, используемая для хранения оценок ученика.

' Может хранить только 1 значение за раз
Dim Student1 As Integer
Student1 = 55

Если мы хотим сохранить оценки другого ученика, нам нужно создать вторую переменную.

В следующем примере у нас есть оценки пяти студентов

VBa Arrays

Мы собираемся прочитать эти отметки и записать их в Immediate Window.

Примечание. Функция Debug.Print записывает значения в Immediate Window. Для просмотра этого окна выберите View-> Immediate Window из меню (сочетание клавиш Ctrl + G).

ImmediateWindow

ImmediateSampeText

Как видите в следующем примере, мы пишем один и тот же код пять раз — по одному для каждого учащегося.

Public Sub StudentMarks()

    With ThisWorkbook.Worksheets("Лист1")

        ' Объявите переменную для каждого студента
        Dim Student1 As Integer
        Dim Student2 As Integer
        Dim Student3 As Integer
        Dim Student4 As Integer
        Dim Student5 As Integer

        ' Читайте оценки студентов из ячейки
        Student1 = .Range("C2").Offset(1)
        Student2 = .Range("C2").Offset(2)
        Student3 = .Range("C2").Offset(3)
        Student4 = .Range("C2").Offset(4)
        Student5 = .Range("C2").Offset(5)

        ' Печать студенческих оценок
        Debug.Print "Оценки студентов"
        Debug.Print Student1
        Debug.Print Student2
        Debug.Print Student3
        Debug.Print Student4
        Debug.Print Student5

    End With

End Sub

Ниже приведен вывод из примера

VBA Arrays

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

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

Public Sub StudentMarksArr()

    With ThisWorkbook.Worksheets("Лист1")

        ' Объявите массив для хранения оценок для 5 студентов
        Dim Students(1 To 5) As Integer

        ' Читайте оценки учеников из ячеек C3: C7 в массив
        Dim i As Integer
        For i = 1 To 5
            Students(i) = .Range("C2").Offset(i)
        Next i

        ' Распечатывать оценки студентов из массива
        Debug.Print "Оценки студентов"
        For i = LBound(Students) To UBound(Students)
            Debug.Print Students(i)
        Next i

    End With

End Sub

Преимущество этого кода в том, что он будет работать для любого количества студентов. Если нам нужно изменить этот код для работы с 1000 студентами, нам нужно всего лишь изменить (от 1 до 5) на (от 1 до 1000) в декларации. В предыдущем примере нам нужно было добавить примерно пять тысяч строк кода.

Давайте проведем быстрое сравнение переменных и массивов. Сначала мы сравним процесс объявления.

 ' Объявляем переменные
        Dim Student As Integer
        Dim Country As String

  ' Объявляем массивы
        Dim Students(1 To 3) As Integer
        Dim Countries(1 To 3) As String

Далее мы сравниваем присвоение значения

    ' присвоить значение переменной
        Student1 = .Cells(1, 1) 

    ' присваивать значение первому элементу в массиве
        Students(1) = .Cells(1, 1)

Наконец, мы смотрим на запись значений

  ' Вывести значение переменной
        Debug.Print Student1

  ' Вывести значение первого студента в массиве
        Debug.Print Students(1)

Как видите, использование переменных и массивов очень похоже.

Важным является тот факт, что массивы используют индекс (также называемый нижним индексом) для доступа к каждому элементу. Это означает, что мы можем легко получить доступ ко всем элементам в массиве, используя цикл For.

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

Типы массивов VBA

В VBA есть два типа массивов:

  1. Статический — массив фиксированного размера.
  2. Динамический — массив, в котором размер задается во время выполнения

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

Объявление массива

Статический массив объявляется следующим образом

Public Sub DecArrayStatic()

    ' Создать массив с местоположениями 0,1,2,3
    Dim arrMarks1(0 To 3) As Long

    ' По умолчанию от 0 до 3, то есть местоположения 0,1,2,3
    Dim arrMarks2(3) As Long

    ' Создать массив с местоположениями 1,2,3,4,5
    Dim arrMarks1(1 To 5) As Long

    ' Создать массив с местоположениями 2,3,4 'Это редко используется
    Dim arrMarks3(2 To 4) As Long

End Sub

VBA Arrays

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

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

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

Public Sub DecArrayDynamic()

    ' Объявить динамический массив
    Dim arrMarks() As Long

    ' Установите размер массива, когда вы будете готовы
    ReDim arrMarks(0 To 5)

End Sub

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

Присвоение значений массиву

Чтобы присвоить значения массиву, вы используете номер местоположения (пересечении строки и столбца). Вы присваиваете значение для обоих типов массивов одинаково.

Public Sub AssignValue()

    ' Объявить массив с местоположениями 0,1,2,3
    Dim arrMarks(0 To 3) As Long

    ' Установите значение позиции 0
    arrMarks(0) = 5

    ' становите значение позиции 3
    arrMarks(3) = 46

    ' Это ошибка, так как нет местоположения 4
    arrMarks(4) = 99

End Sub

VBA Array 2

Номер места называется индексом. Последняя строка в примере выдаст ошибку «Индекс вне диапазона», так как в примере массива нет местоположения 4.

Использование функций Array и Split

Вы можете использовать функцию Array для заполнения массива списком элементов. Вы должны объявить массив как тип Variant. Следующий код показывает, как использовать эту функцию.

  Dim arr1 As Variant
    arr1 = Array("Апельсин", "Персик","Груша")

  Dim arr2 As Variant
    arr2 = Array(5, 6, 7, 8, 12)

Arrays VBA

Массив, созданный функцией Array, начнется с нулевого индекса, если вы не используете Option Base 1 в верхней части вашего модуля. Затем он начнется с первого индекса. В программировании, как правило, считается плохой практикой иметь ваши реальные данные в коде. Однако иногда это полезно, когда вам нужно быстро протестировать некоторый код. Функция Split используется для разделения строки на массив на основе разделителя. Разделитель — это символ, такой как запятая или пробел, который разделяет элементы.

Следующий код разделит строку на массив из трех элементов.

 Dim s As String
    s = "Красный,Желтый,Зеленый,Синий"

    Dim arr() As String
    arr = Split(s, ",")

Arrays VBA

Функция Split обычно используется, когда вы читаете из cvs или txt-файла, разделенного запятыми, или из другого источника, который предоставляет список элементов, разделенных одним и тем же символом.

Использование циклов с массивами

Использование цикла For обеспечивает быстрый доступ ко всем элементам массива. Вот где сила использования массивов становится очевидной. Мы можем читать массивы с десятью значениями или десятью тысячами значений, используя те же несколько строк кода. В VBA есть две функции: LBound и UBound. Эти функции возвращают самый маленький и самый большой индекс в массиве. В массиве arrMarks (от 0 до 3) LBound вернет 0, а UBound вернет 3.

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

Public Sub ArrayLoops()

    ' Объявить массив
    Dim arrMarks(0 To 5) As Long

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' Распечатайте значения в массиве
    Debug.Print "Место нахождения", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

Функции LBound и UBound очень полезны. Их использование означает, что наши циклы будут работать правильно с любым размером массива. Реальное преимущество заключается в том, что если размер массива изменяется, нам не нужно менять код для печати значений. Цикл будет работать для массива любого размера, пока вы используете эти функции.

Использование цикла For Each

Вы можете использовать цикл For Each с массивами. Важно помнить, что он доступен только для чтения. Это означает, что вы не можете изменить значение в массиве.

В следующем коде значение метки изменяется, но оно не меняет значение в массиве.

 For Each mark In arrMarks
        ' Не изменит значение массива
        mark = 5 * Rnd
    Next mark

Цикл For Each отлично подходит для чтения массива. Как видите, лучше писать специально для двумерного массива.

  Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Использование Erase

Функция Erase может использоваться для массивов, но она работает по-разному в зависимости от типа массива.

Для статического массива функция Erase сбрасывает все значения по умолчанию. Если массив состоит из целых чисел, то все значения устанавливаются в ноль. Если массив состоит из строк, то все строки устанавливаются в «» и так далее.

Для динамического массива функция удаления стирает память. То есть она удаляет массив. Если вы хотите использовать его снова, вы должны использовать ReDim для выделения памяти.

Давайте рассмотрим пример статического массива. Этот пример аналогичен примеру ArrayLoops в последнем разделе с одним отличием — мы используем Erase после установки значений. Когда значение будет распечатано, все они будут равны нулю.

Public Sub EraseStatic()

    ' Объявить массив
    Dim arrMarks(0 To 3) As Long

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' ВСЕ ЗНАЧЕНИЯ УСТАНОВЛЕНЫ НА НОЛЬ
    Erase arrMarks

    ' Распечатайте значения - там все теперь ноль
    Debug.Print "Место нахождения", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

Теперь мы попробуем тот же пример с динамикой. После того, как мы используем Erase, все места в массиве были удалены. Нам нужно использовать ReDim, если мы хотим использовать массив снова.

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

Public Sub EraseDynamic()

    ' Объявить массив
    Dim arrMarks() As Long
    ReDim arrMarks(0 To 3)

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' arrMarks теперь освобожден. Места не существуют.
    Erase arrMarks

End Sub

ReDim с Preserve

Если мы используем ReDim для существующего массива, то массив и его содержимое будут удалены.

В следующем примере второй оператор ReDim создаст совершенно новый массив. Исходный массив и его содержимое будут удалены.

Sub UsingRedim()

    Dim arr() As String
    
    ' Установить массив в слоты от 0 до 2
    ReDim arr(0 To 2)
    arr(0) = "Яблоко"
    
    ' Массив с яблоком теперь удален
    ReDim arr(0 To 3)

End Sub

Если мы хотим расширить размер массива без потери содержимого, мы можем использовать ключевое слово Preserve.

Когда мы используем Redim Preserve, новый массив должен начинаться с того же начального размера, например мы не можем сохранить от (0 до 2) до (от 1 до 3) или до (от 2 до 10), поскольку они являются различными начальными размерами.

В следующем коде мы создаем массив с использованием ReDim, а затем заполняем массив типами фруктов.

Затем мы используем Preserve для увеличения размера массива, чтобы не потерять оригинальное содержимое.

Sub UsingRedimPreserve()

    Dim arr() As String
    
    ' Установить массив в слоты от 0 до 1
    ReDim arr(0 To 2)
    arr(0) = "Яблоко"
    arr(1) = "Апельсин"
    arr(2) = "Груша"
    
    ' Изменение размера и сохранение исходного содержимого
    ReDim Preserve arr(0 To 5)

End Sub

Из приведенных ниже снимков экрана видно, что исходное содержимое массива было «сохранено».

VBA Preserve

VBA Preserve

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

Использование Preserve с 2-мерными массивами

Preserve работает только с верхней границей массива.

Например, если у вас есть двумерный массив, вы можете сохранить только второе измерение, как показано в следующем примере:

Sub Preserve2D()

    Dim arr() As Long
    
    ' Установите начальный размер
    ReDim arr(1 To 2, 1 To 5)
    
    ' Изменить размер верхнего измерения
    ReDim Preserve arr(1 To 2, 1 To 10)

End Sub

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

В следующем коде мы используем Preserve для первого измерения. Запуск этого кода приведет к ошибке «Индекс вне диапазона»:

Sub Preserve2DError()

    Dim arr() As Long
    
    ' Установите начальный размер
    ReDim arr(1 To 2, 1 To 5)
    
    ' Ошибка «Вне диапазона»
    ReDim Preserve arr(1 To 5, 1 To 5)

End Sub

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

Применяются те же правила сохранения. Мы можем использовать Preserve только на верхней границе, как показано в следующем примере:

Sub Preserve2DRange()

    Dim arr As Variant
    
    ' Назначить диапазон массиву
    arr = Sheet1.Range("A1:A5").Value
    
    ' Preserve будет работать только на верхней границе
    ReDim Preserve arr(1 To 5, 1 To 7)

End Sub

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

В VBA нет функции для сортировки массива. Мы можем отсортировать ячейки листа, но это медленно, если данных много.

Функция быстрой сортировки ниже может использоваться для сортировки массива.

Sub QuickSort(arr As Variant, first As Long, last As Long)
  
  Dim vCentreVal As Variant, vTemp As Variant
  
  Dim lTempLow As Long
  Dim lTempHi As Long
  lTempLow = first
  lTempHi = last
  
  vCentreVal = arr((first + last) / 2)
  Do While lTempLow <= lTempHi
  
    Do While arr(lTempLow) < vCentreVal And lTempLow < last
      lTempLow = lTempLow + 1
    Loop
    
    Do While vCentreVal < arr(lTempHi) And lTempHi > first
      lTempHi = lTempHi - 1
    Loop
    
    If lTempLow <= lTempHi Then
    
        ' Поменять значения
        vTemp = arr(lTempLow)

        arr(lTempLow) = arr(lTempHi)
        arr(lTempHi) = vTemp
      
        ' Перейти к следующим позициям
        lTempLow = lTempLow + 1
        lTempHi = lTempHi - 1
      
    End If
    
  Loop
  
  If first < lTempHi Then QuickSort arr, first, lTempHi
  If lTempLow < last Then QuickSort arr, lTempLow, last
  
End Sub

Вы можете использовать эту функцию так:

Sub TestSort()

    ' Создать временный массив
    Dim arr() As Variant
    arr = Array("Банан", "Дыня", "Персик", "Слива", "Яблоко")
  
    ' Сортировать массив
    QuickSort arr, LBound(arr), UBound(arr)

    ' Печать массива в Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i

End Sub

Передача массива в Sub или функцию

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

Переход к процедуре с использованием ByRef означает, что вы передаете ссылку на массив. Таким образом, если вы измените массив в процедуре, он будет изменен, когда вы вернетесь.

 Примечание. Когда вы используете массив в качестве параметра, он не может использовать ByVal, он должен использовать ByRef. Вы можете передать массив с помощью ByVal, сделав параметр вариантом.

' Передает массив в функцию
Public Sub PassToProc()
    Dim arr(0 To 5) As String
    ' Передать массив в функцию
    UseArray arr
End Sub

Public Function UseArray(ByRef arr() As String)
    ' Использовать массив
    Debug.Print UBound(arr)
End Function

Возвращение массива из функции

Важно помнить следующее. Если вы хотите изменить существующий массив в процедуре, вы должны передать его как параметр, используя ByRef (см. Последний раздел). Вам не нужно возвращать массив из процедуры.

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

Следующие примеры показывают это:

Public Sub TestArray()

    ' Объявить динамический массив - не выделен
    Dim arr() As String
    ' Возврат нового массива
    arr = GetArray

End Sub

Public Function GetArray() As String()

    ' Создать и выделить новый массив
    Dim arr(0 To 5) As String
    ' Возвращаемый массив
    GetArray = arr

End Function

Двумерные массивы

Массивы, на которые мы смотрели до сих пор, были одномерными. Это означает, что массивы представляют собой один список элементов.

Двумерный массив — это список списков. Если вы думаете об одной строке электронной таблицы как об одном измерении, то более одного столбца является двухмерным. На самом деле электронная таблица является эквивалентом двумерного массива. Он имеет два измерения — строки и столбцы.

Следует отметить одну маленькую вещь: Excel обрабатывает одномерный массив как строку, если вы записываете его в электронную таблицу. Другими словами, массив arr (от 1 до 5) эквивалентен arr (от 1 до 1, от 1 до 5) при записи значений в электронную таблицу.

На следующем рисунке показаны две группы данных. Первый — это одномерный массив, а второй — двухмерный.

VBA Array Dimension

Чтобы получить доступ к элементу в первом наборе данных (одномерном), все, что вам нужно сделать, это дать строку, например. 1,2, 3 или 4.

Для второго набора данных (двумерного) вам нужно указать строку И столбец. Таким образом, вы можете думать, что 1-мерное — это несколько столбцов, а одна строка и двухмерное — это несколько строк и несколько столбцов.

Примечание. В массиве может быть более двух измерений. Это редко требуется. Если вы решаете проблему с помощью 3+-мерного массива, то, вероятно, есть лучший способ сделать это.

Вы объявляете двумерный массив следующим образом:

Dim ArrayMarks(0 To 2, 0 To 3) As Long

В следующем примере создается случайное значение для каждого элемента в массиве и печатается значение в Immediate Window.

Public Sub TwoDimArray()

    ' Объявить двумерный массив
    Dim arrMarks(0 To 3, 0 To 2) As String

    ' Заполните массив текстом, состоящим из значений i и j
    Dim i As Long, j As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            arrMarks(i, j) = CStr(i) & ":" & CStr(j)
        Next j
    Next i

    ' Вывести значения в массиве в Immediate Window
    Debug.Print "i", "j", "Знаечние"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

End Sub

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

Результат примера выглядит следующим образом:

VBA Arrays

Этот макрос работает следующим образом:

  • Входит в цикл i
  • i установлен на 0
  • цикл Enters j
  • j установлен на 0
  • j установлен в 1
  • j установлен на 2
  • Выход из цикла j
  • i установлен в 1
  • j установлен на 0
  • j установлен в 1
  • j установлен на 2
  • И так до тех пор, пока i = 3 и j = 2

Заметьте, что LBound и UBound имеют второй аргумент 2. Это указывает, что это верхняя или нижняя граница второго измерения. Это начальное и конечное местоположение для j. Значение по умолчанию 1, поэтому нам не нужно указывать его для цикла i.

Использование цикла For Each

Использование For Each лучше использовать при чтении из массива.
Давайте возьмем код сверху, который выписывает двумерный массив.

 ' Для цикла For необходимо два цикла
    Debug.Print "i", "j", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

Теперь давайте перепишем его, используя цикл For Each. Как видите, нам нужен только один цикл, и поэтому гораздо проще написать:

 ' Использование For Each требует только одного цикла
    Debug.Print "Значение"
    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Использование цикла For Each дает нам массив только в одном порядке — от LBound до UBound. В большинстве случаев это все, что вам нужно.

Чтение из диапазона ячеек в массив

Если вы читали мою статью о ячейках и диапазонах, то вы знаете, что VBA имеет чрезвычайно эффективный способ чтения из диапазона ячеек в массив и наоборот.

Public Sub ReadToArray()

    ' Объявить динамический массив
    Dim StudentMarks As Variant

    ' Считать значения в массив из первой строки
    StudentMarks = Range("A1:Z1").Value

    ' Запишите значения обратно в третий ряд
    Range("A3:Z3").Value = StudentMarks

End Sub

Динамический массив, созданный в этом примере, будет двухмерным массивом. Как видите, мы можем прочитать весь диапазон ячеек в массив всего за одну строку.

В следующем примере будут считаны примеры данных студента ниже из C3: E6 Лист1 и распечатаны в Immediate Window.

Public Sub ReadAndDisplay()

    ' Получить диапазон
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Лист1").Range("C3:E6")

    ' Создать динамический массив
    Dim StudentMarks As Variant

    ' Считать значения в массив из листа 1
    StudentMarks = rg.Value

    ' Вывести значения массива
    Debug.Print "i", "j", "Значение"
    Dim i As Long, j As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        For j = LBound(StudentMarks, 2) To UBound(StudentMarks, 2)
            Debug.Print i, j, StudentMarks(i, j)
        Next j
    Next i

End Sub

VBA 2D Array

VBA 2D Array Output

Как видите, первое измерение (доступное через i) массива — это строка, а второе — столбец. Чтобы продемонстрировать это, взглянем на значение 44 в Е4 данных образца. Это значение находится в строке 2 столбца 3 наших данных. Вы можете видеть, что 44 хранится в массиве в StudentMarks (2,3).

Как заставить ваши макросы работать на суперскорости

Если ваши макросы работают очень медленно, этот раздел будет очень полезным. Особенно, если вы имеете дело с большими объемами данных. В VBA это держится в секрете.

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

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

  1. Скопируйте данные из ячеек в массив.
  2. Измените данные в массиве.
  3. Скопируйте обновленные данные из массива обратно в ячейки.

Например, следующий код будет намного быстрее, чем код ниже:

Public Sub ReadToArray()

    ' Считать значения в массив из первой строки
    Dim StudentMarks  As Variant
    StudentMarks = Range("A1:Z20000").Value

    Dim i As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        ' Обновление отметок здесь
        StudentMarks(i, 1) = StudentMarks(i, 1) * 2
        '...
    Next i

    ' Запишите новые значения обратно на лист
    Range("A1:Z20000").Value = StudentMarks

End Sub
Sub UsingCellsToUpdate()
    
    Dim c As Variant
    For Each c In Range("A1:Z20000")
        c.Value = ' Обновите значения здесь
    Next c
    
End Sub

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

' Назначение - быстрее
Range("A1:A10").Value = Range("B1:B10").Value

' Копировать Вставить - медленнее
Range("B1:B1").Copy Destination:=Range("A1:A10")

Заключение

Ниже приводится краткое изложение основных моментов этой статьи.

  1. Массивы — это эффективный способ хранения списка элементов одного типа.
  2. Вы можете получить доступ к элементу массива напрямую, используя номер местоположения, который известен как индекс.
  3. Распространенная ошибка «Индекс вне диапазона» вызвана доступом к несуществующему местоположению.
  4. Существует два типа массивов: статический и динамический.
  5. Статический используется, когда размер массива всегда одинаков.
  6. Динамические массивы позволяют вам определять размер массива во время выполнения.
  7. LBound и UBound обеспечивают безопасный способ поиска самых маленьких и самых больших подписок массива.
  8. Основной массив является одномерным. Есть еще многомерные массивы.
  9. Чтобы только передать массив в процедуру, используйте ByRef. Вы делаете это так: ByRef arr() as long.
  10. Вы можете вернуть массив из функции, но массив, которому он назначен, не должен быть выделен в данный момент.
  11. Рабочий лист с его строками и столбцами по сути является двумерным массивом.
  12. Вы можете читать непосредственно из диапазона листа в двухмерный массив всего за одну строку кода.
  13. Вы также можете записать из двумерного массива в диапазон всего за одну строку кода.

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

Время на прочтение
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

Понравилась статья? Поделить с друзьями:
  • Excel vba обновить запросы
  • Excel vba массивы присвоение значений
  • Excel vba обновить запрос
  • Excel vba обновить все подключения
  • Excel vba массивы данных