Excel vba array index

Dim pos, arr, val

arr=Array(1,2,4,5)
val = 4

pos=Application.Match(val, arr, False)

if not iserror(pos) then
   Msgbox val & " is at position " & pos
else
   Msgbox val & " not found!"
end if

Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:

Dim arr(1 To 10, 1 To 2)
Dim x

For x = 1 To 10
    arr(x, 1) = x
    arr(x, 2) = 11 - x
Next x

Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)

EDIT: it’s worth illustrating here what @ARich pointed out in the comments — that using Index() to slice an array has horrible performance if you’re doing it in a loop.

In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.

Sub PerfTest()

    Const VAL_TO_FIND As String = "R1800:C8"
    Dim a(1 To 2000, 1 To 10)
    Dim r As Long, c As Long, t

    For r = 1 To 2000
        For c = 1 To 10
            a(r, c) = "R" & r & ":C" & c
        Next c
    Next r

    t = Timer
    Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
    ' >> 0.00781 sec

     t = Timer
    Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
    ' >> 14.18 sec

End Sub

Function FindLoop(arr, val) As Boolean
    Dim r As Long, c As Long
    For r = 1 To UBound(arr, 1)
    For c = 1 To UBound(arr, 2)
        If arr(r, c) = val Then
            FindLoop = True
            Exit Function
        End If
    Next c
    Next r
End Function

Function FindIndex(arr, val)
    Dim r As Long
    For r = 1 To UBound(arr, 1)
        If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
            FindIndex = True
            Exit Function
        End If
    Next r
End Function

Содержание

  1. WorksheetFunction.Index method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Array form
  7. Reference form
  8. Support and feedback
  9. Return Position of Element in VBA Array
  10. The VBA Tutorials Blog
  11. VBA Find Index in Array
  12. How to use the WhereInArray Function
  13. Why a Variant?
  14. Return Index of an Element in an Array Excel VBA
  15. 7 Answers 7
  16. VBA Массивы
  17. Объявление массива в VBA
  18. Доступ к элементам
  19. Индексирование массива
  20. Специфический указатель
  21. Динамическая декларация
  22. Использование Split для создания массива из строки
  23. Итерирующие элементы массива
  24. Для . Далее
  25. Для каждого . Далее
  26. Динамические массивы (изменение размера массива и динамическая обработка)
  27. Динамические массивы
  28. Добавление значений динамически
  29. Удаление значений динамически
  30. Сброс массива и повторное использование динамически
  31. Жесткие массивы (массивы массивов)
  32. Ядра массивов НЕ многомерные массивы
  33. Создание поврежденного массива
  34. Динамическое создание и чтение массивов с зубцами
  35. Многомерные массивы
  36. Многомерные массивы
  37. Двухмерный массив
  38. Трехмерный массив

WorksheetFunction.Index method (Excel)

Returns a value or the reference to a value from within a table or range. There are two forms of the Index function: the array form and the reference form.

Syntax

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required Variant Array or Reference — a range of cells or an array constant. For references, it is the reference to one or more cell ranges.
Arg2 Required Double Row_num — selects the row in array from which to return a value. If row_num is omitted, column_num is required. For references, the number of the row in reference from which to return a reference.
Arg3 Optional Variant Column_num — selects the column in array from which to return a value. If column_num is omitted, row_num is required. For reference, the number of the column in reference from which to return a reference.
Arg4 Optional Variant Area_num — only used when returning references. Selects a range in reference from which to return the intersection of row_num and column_num. The first area selected or entered is numbered 1, the second is 2, and so on. If area_num is omitted, Index uses area 1.

Return value

Variant

Array form

Returns the value of an element in a table or an array, selected by the row and column number indexes.

Use the array form if the first argument to Index is an array constant.

If both the row_num and column_num arguments are used, Index returns the value in the cell at the intersection of row_num and column_num.

If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively. To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row, and in a vertical range of cells for a column. To enter an array formula, press Ctrl+Shift+Enter.

Row_num and column_num must point to a cell within array; otherwise, Index returns the #REF! error value.

Reference form

Returns the reference of the cell at the intersection of a particular row and column. If the reference is made up of nonadjacent selections, you can pick the selection to look in. If each area in reference contains only one row or column, the row_num or column_num argument, respectively, is optional. For example, for a single row reference, use INDEX(reference,column_num).

After reference and area_num have selected a particular range, row_num and column_num select a particular cell: row_num 1 is the first row in the range, column_num 1 is the first column, and so on. The reference returned by Index is the intersection of row_num and column_num.

If you set row_num or column_num to 0 (zero), Index returns the reference for the entire column or row, respectively.

Row_num, column_num, and area_num must point to a cell within reference; otherwise, Index returns the #REF! error value. If row_num and column_num are omitted, Index returns the area in reference specified by area_num.

The result of the Index function is a reference and is interpreted as such by other formulas. Depending on the formula, the return value of Index may be used as a reference or as a value. For example, the formula CELL(«width»,INDEX(A1:B2,1,2)) is equivalent to CELL(«width»,B1) . The CELL function uses the return value of Index as a cell reference. On the other hand, a formula such as 2*INDEX(A1:B2,1,2) translates the return value of Index into the number in cell B1.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Return Position of Element in VBA Array

The VBA Tutorials Blog

Return the position of an element in an array with this function from the VBA Code Library. This UDF is a great tool to have when working with arrays containing unknown elements.

A lot of people recommend using the worksheet function Index to return the position in a VBA array, but I’ve found the performance of that function to be rather slow. Although it loops through each element in your array, I prefer this function.

VBA Find Index in Array

Make powerful macros with our free VBA Developer Kit

Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.

Looping through the elements in an array until you find a match is an essential skill, but you can do so much more with arrays. To become really good at using arrays, you’ll need to grab a copy of our comprehensive VBA Arrays Cheat Sheet with over 20 pre-built macros and dozens of tips designed to make it easy for you to handle arrays.

How to use the WhereInArray Function

The WhereInArray UDF accepts two arguments:

  • arr1 — the array you want to search
  • vFind — the value you want to find in your array.

The function returns the position of the element in your array. If the function can’t find the element in your array, it returns a null string. This is an important to note because if you try to assign this function to an integer or long data type and the element isn’t in your array, you’ll get an error.

Let’s take a look at some examples. We’ll look at a couple good demonstrations, and one bad demonstration.

This example tries to find the string “cat” in an array a . “Cat” is stored in the 1st index position (0, 1, 2), so the function returns a value of 1.

In this example, we’ll try to find the word “meow” in the array a . Notice that “meow” isn’t in the array. When we search for it, the WhereInArray function returns a value of Null.

The example above only works because the variable i was declared as a Variant. If it were defined as a Long or an Integer, it would generate Run-time Error 94, “Invalid use of Null.”

This what I mean. In this demonstration, we’ll run the same macro except we’ll declare the variable i as an integer.

Like I promised, you get a run-time error.

Why a Variant?

Why do I prefer to output my index position as a variant instead of a long or integer? I do this so I can use this function in two different ways.

If I don’t really care where the element is in the array but I want to know whether or not the element is in the array, I can check for Null using the IsNull function to see if the value I’m curious about is anywhere in my array. In that regard, it functions like my IsInArray UDF.

Take a look at this example to see what I mean:

For more VBA tips, techniques, and tactics, subscribe to our VBA Insiders email series using the form below. Once you join, share this article on Twitter and Facebook.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

Return Index of an Element in an Array Excel VBA

I have an array prLst that is a list of integers. The integers are not sorted, because their position in the array represents a particular column on a spreadsheet. I want to know how I find a particular integer in the array, and return its index.

There does not seem to be any resource on showing me how without turning the array into a range on the worksheet. This seems a bit complicated. Is this just not possible with VBA?

7 Answers 7

Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:

EDIT: it’s worth illustrating here what @ARich pointed out in the comments — that using Index() to slice an array has horrible performance if you’re doing it in a loop.

In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.

array of variants:

a fastest version for integers (as pref tested below)

a snippet, lets test the assumption the passing by reference as argument means something. (the answer is no) to use it replace myList and myValue to your variable names:

to prove the point I have made some benchmarks

here are the results:

a class named PerformanceMonitor

Here’s another way:

Is this what you are looking for?

Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.

The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with «/[column number]//|» as the delimiter.

& use a single-cell result multiple lookupall macro function on the this 1-d column.

& then index match to pull out the positions. (usuing multiple find match)

That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.

Wish I could write a macro / function for this entire process. It would save me more fuss.

Источник

VBA
Массивы

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

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

По умолчанию массивы в VBA индексируются из ZERO , поэтому число внутри скобки не относится к размеру массива, а скорее к индексу последнего элемента

Доступ к элементам

Доступ к элементу массива осуществляется с использованием имени массива, за которым следует индекс элемента, внутри скобки:

Индексирование массива

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

С этой строкой все объявленные в модуле массивы будут проиндексированы с ONE .

Специфический указатель

Вы также можете объявить каждый массив своим собственным индексом, используя ключевое слово To , а нижнюю и верхнюю границы (= индекс):

Динамическая декларация

Когда вы не знаете размер своего массива до его объявления, вы можете использовать динамическое объявление и ключевое слово ReDim :

Обратите внимание, что использование ключевого слова ReDim уничтожит любое предыдущее содержимое вашего массива. Чтобы предотвратить это, вы можете использовать ключевое слово Preserve после ReDim :

Использование Split для создания массива из строки

Функция разделения

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

Синтаксис

Split (выражение [, разделитель [, limit [, compare ]]] )

Часть Описание
выражение Необходимые. Строковое выражение, содержащее подстроки и разделители. Если выражение представляет собой строку нулевой длины («» или vbNullString), Split возвращает пустой массив, не содержащий элементов и данных. В этом случае возвращаемый массив будет иметь LBound 0 и UBound -1.
ограничитель Необязательный. Строковый символ, используемый для определения пределов подстроки. Если опустить, символ пробела («») считается разделителем. Если разделителем является строка с нулевой длиной, возвращается одноэлементный массив, содержащий всю строку выражения .
предел Необязательный. Количество подстрок, подлежащих возврату; -1 указывает, что все подстроки возвращаются.
сравнить Необязательный. Числовое значение, указывающее, какое сравнение следует использовать при оценке подстрок. См. Раздел «Настройки» для значений.

настройки

Аргумент сравнения может иметь следующие значения:

постоянная Значение Описание
Описание -1 Выполняет сравнение, используя настройку оператора сравнения параметров .
vbBinaryCompare 0 Выполняет двоичное сравнение.
vbTextCompare 1 Выполняет текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняет сравнение, основанное на информации в вашей базе данных.

пример

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

Итерирующие элементы массива

Для . Далее

Использование переменной итератора в качестве номера индекса является самым быстрым способом для итерации элементов массива:

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

Для каждого . Далее

A For Each. Next цикл также может использоваться для повторения массивов, если производительность не имеет значения:

A For Each цикла будут выполняться итерация всех измерений от внешнего к внутреннему (в том же порядке, что и элементы, выделенные в памяти), поэтому нет необходимости в вложенных циклах:

Обратите внимание, что For Each петли лучше всего использовать для итерации объектов Collection , если имеет значение производительность.

Все 4 фрагмента выше дают одинаковый результат:

Динамические массивы (изменение размера массива и динамическая обработка)

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

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

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

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

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

Удаление значений динамически

Мы можем использовать ту же логику для уменьшения массива. В этом примере значение «последний» будет удалено из массива.

Сброс массива и повторное использование динамически

Мы также можем повторно использовать массивы, которые мы создаем, чтобы не иметь много памяти, что замедлит работу. Это полезно для массивов разных размеров. Один фрагмент кода можно использовать повторно использовать массив в ReDim массив обратно (0) , приписывать одной переменной в массив и снова свободно увеличивать массив.

В нижеприведенном фрагменте я создаю массив со значениями от 1 до 40, пуст массив и пополняем массив значениями от 40 до 100, все это выполняется динамически.

Жесткие массивы (массивы массивов)

Ядра массивов НЕ многомерные массивы

Массивы массивов (Jagged Arrays) не совпадают с многомерными массивами, если вы думаете о них визуально. Многомерные массивы будут выглядеть как Matrices (Rectangular) с определенным количеством элементов по их размерам (внутри массивов), в то время как массив Jagged будет похож на ежегодный календарь с внутренними массивами, имеющими различное количество элементов, например, дни в разные месяцы.

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

Создание поврежденного массива

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

Динамическое создание и чтение массивов с зубцами

Мы также можем быть более динамичными в нашем приближении, чтобы построить массивы, представьте, что у нас есть личный лист данных клиентов в excel, и мы хотим построить массив для вывода информации о клиенте.

Мы будем динамически строить массив заголовков и массив Customers, заголовок будет содержать заголовки столбцов, а массив Customers будет содержать информацию каждого клиента / строки в виде массивов.

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

Результатом приведенного выше фрагмента является массив с чередованием с двумя массивами, один из тех массивов с 4 элементами, 2 уровня отступа, а другой сам по себе является другим массивом Jagged, содержащим 5 массивов из 4 элементов каждый и 3 уровня отступа, см. Ниже структуру:

Чтобы получить доступ к информации, которую вы должны иметь в виду о структуре созданного массива Jagged Array, в приведенном выше примере вы можете видеть, что Main Array содержит массив Headers и массив массивов ( Customers ), следовательно, с различными способами доступ к элементам.

Теперь мы прочитаем информацию о Main Array и распечатаем каждую из данных Клиентов в виде Info Type: Info .

ЗАПОМНИТЕ, чтобы отслеживать структуру вашего Jagged Array, в приведенном выше примере для доступа к имени клиента, Main_Array -> Customers -> CustomerNumber -> Name к Main_Array -> Customers -> CustomerNumber -> Name который состоит из трех уровней, для возврата «Person4» вам понадобится расположение клиентов в Main_Array, затем местоположение клиента 4 в массиве Jagged Customers и, наконец, местоположение Main_Array(1)(3)(0) элемента в этом случае Main_Array(1)(3)(0) который является Main_Array(Customers)(CustomerNumber)(Name) .

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

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

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

Массив массива работает как матрица с различными уровнями, например, сравнение между одним, двумя и тремя измерениями.

Одно измерение — ваш типичный массив, он выглядит как список элементов.

Два измерения будут выглядеть как сетка Sudoku или лист Excel, при инициализации массива вы определяете, сколько строк и столбцов будет иметь массив.

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

Дальнейшие измерения можно рассматривать как умножение 3D, поэтому 4D (1,3,3,3) будет представлять собой два боковых боковых 3D-массива.

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

Создание

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

Изменение размера

Изменение размера или ReDim Preserve Multi-Array, как и норма для массива One-Dimension, приведет к ошибке, вместо этого информация должна быть перенесена в массив Temporary с тем же размером, что и оригинал, плюс число добавляемых строк / столбцов. В приведенном ниже примере мы увидим, как инициализировать Temp Array, передать информацию из исходного массива, заполнить оставшиеся пустые элементы и заменить массив temp на исходный массив.

Изменение значений элементов

Изменение / изменение значений в определенном элементе может быть выполнено путем простого вызова координаты для изменения и предоставления ей нового значения: Employees(0, 0) = «NewValue»

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

чтение

Доступ к элементам в массиве может выполняться с помощью вложенного цикла (итерация каждого элемента), цикла и координат (итерации строк и доступа к столбцам напрямую) или прямого доступа к обеим координатам.

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

Трехмерный массив

Для 3D-массива мы будем использовать ту же предпосылку, что и 2D-массив, с добавлением не только хранения Employee и Information, но и построения, в котором они работают.

В трехмерном массиве будут присутствовать сотрудники (могут рассматриваться как строки), информация (столбцы) и здание, которые можно рассматривать как разные листы на документе excel, они имеют одинаковый размер между ними, но каждый лист имеет различный набор информации в своих ячейках / элементах. 3D-массив будет содержать n число 2D-массивов.

Создание

3D-массив нуждается в трех координатах для инициализации Dim 3Darray(2,5,5) As Variant первой координатой массива будет количество строений / таблиц (разные наборы строк и столбцов), вторая координата будет определять строки и третью Столбцы. В результате Dim выше будет создан трехмерный массив с 108 элементами ( 3*6*6 ), эффективно имеющий 3 разных набора 2D-массивов.

Изменение размера

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

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

Изменение значений элементов и чтение

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

Источник

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

Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings

По умолчанию массивы в VBA индексируются из ZERO , поэтому число внутри скобки не относится к размеру массива, а скорее к индексу последнего элемента

Доступ к элементам

Доступ к элементу массива осуществляется с использованием имени массива, за которым следует индекс элемента, внутри скобки:

myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"

Индексирование массива

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

Option Base 1

С этой строкой все объявленные в модуле массивы будут проиндексированы с ONE .

Специфический указатель

Вы также можете объявить каждый массив своим собственным индексом, используя ключевое слово To , а нижнюю и верхнюю границы (= индекс):

Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24

Динамическая декларация

Когда вы не знаете размер своего массива до его объявления, вы можете использовать динамическое объявление и ключевое слово ReDim :

Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements

Обратите внимание, что использование ключевого слова ReDim уничтожит любое предыдущее содержимое вашего массива. Чтобы предотвратить это, вы можете использовать ключевое слово Preserve после ReDim :

Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"

ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element

Использование Split для создания массива из строки

Функция разделения

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

Синтаксис

Split (выражение [, разделитель [, limit [, compare ]]] )

Часть Описание
выражение Необходимые. Строковое выражение, содержащее подстроки и разделители. Если выражение представляет собой строку нулевой длины («» или vbNullString), Split возвращает пустой массив, не содержащий элементов и данных. В этом случае возвращаемый массив будет иметь LBound 0 и UBound -1.
ограничитель Необязательный. Строковый символ, используемый для определения пределов подстроки. Если опустить, символ пробела («») считается разделителем. Если разделителем является строка с нулевой длиной, возвращается одноэлементный массив, содержащий всю строку выражения .
предел Необязательный. Количество подстрок, подлежащих возврату; -1 указывает, что все подстроки возвращаются.
сравнить Необязательный. Числовое значение, указывающее, какое сравнение следует использовать при оценке подстрок. См. Раздел «Настройки» для значений.

настройки

Аргумент сравнения может иметь следующие значения:

постоянная Значение Описание
Описание -1 Выполняет сравнение, используя настройку оператора сравнения параметров .
vbBinaryCompare 0 Выполняет двоичное сравнение.
vbTextCompare 1 Выполняет текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняет сравнение, основанное на информации в вашей базе данных.

пример

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

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

    textArray = Split("172.23.56.4", ".")
    'Result: {"172", "23", "56", "4"}

    textArray = Split("A;B;C;D", ";")
    'Result: {"A", "B", "C", "D"}

    textArray = Split("A;B;C;D", ";", 1)
    'Result: {"A;B;C;D"}

    textArray = Split("A;B;C;D", ";", 2)
    'Result: {"A", "B;C;D"}

    textArray = Split("A;B;C;D", ";", 3)
    'Result: {"A", "B", "C;D"}

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

Итерирующие элементы массива

Для … Далее

Использование переменной итератора в качестве номера индекса является самым быстрым способом для итерации элементов массива:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

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

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

Для каждого … Далее

A For Each...Next цикл также может использоваться для повторения массивов, если производительность не имеет значения:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

A For Each цикла будут выполняться итерация всех измерений от внешнего к внутреннему (в том же порядке, что и элементы, выделенные в памяти), поэтому нет необходимости в вложенных циклах:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

Обратите внимание, что For Each петли лучше всего использовать для итерации объектов Collection , если имеет значение производительность.


Все 4 фрагмента выше дают одинаковый результат:

 0
 1
 2
 3

Динамические массивы (изменение размера массива и динамическая обработка)

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

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

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

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

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

Dim Dynamic_array As Variant
' first we set Dynamic_array as variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        'isempty() will check if we need to add the first value to the array or subsequent ones
    
        ReDim Dynamic_array(0)
        'ReDim Dynamic_array(0) will resize the array to one variable only
        Dynamic_array(0) = n

    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
        Dynamic_array(UBound(Dynamic_array)) = n
        'attribute a value to the last variable of Dynamic_array
    End If

Next

Удаление значений динамически

Мы можем использовать ту же логику для уменьшения массива. В этом примере значение «последний» будет удалено из массива.

Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
    
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value

Сброс массива и повторное использование динамически

Мы также можем повторно использовать массивы, которые мы создаем, чтобы не иметь много памяти, что замедлит работу. Это полезно для массивов разных размеров. Один фрагмент кода можно использовать повторно использовать массив в ReDim массив обратно (0) , приписывать одной переменной в массив и снова свободно увеличивать массив.

В нижеприведенном фрагменте я создаю массив со значениями от 1 до 40, пуст массив и пополняем массив значениями от 40 до 100, все это выполняется динамически.

Dim Dynamic_array As Variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        ReDim Dynamic_array(0)
        Dynamic_array(0) = n
    
    ElseIf Dynamic_array(0) = "" Then
        'if first variant is empty ( = "") then give it the value of n
        Dynamic_array(0) = n
    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        Dynamic_array(UBound(Dynamic_array)) = n
    End If
    If n = 40 Then
        ReDim Dynamic_array(0)
        'Resizing the array back to one variable without Preserving,
        'leaving the first value of the array empty
    End If

Next

Жесткие массивы (массивы массивов)

Ядра массивов НЕ многомерные массивы

Массивы массивов (Jagged Arrays) не совпадают с многомерными массивами, если вы думаете о них визуально. Многомерные массивы будут выглядеть как Matrices (Rectangular) с определенным количеством элементов по их размерам (внутри массивов), в то время как массив Jagged будет похож на ежегодный календарь с внутренними массивами, имеющими различное количество элементов, например, дни в разные месяцы.

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

Создание поврежденного массива

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

Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements

Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")

OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside

Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element

Динамическое создание и чтение массивов с зубцами

Мы также можем быть более динамичными в нашем приближении, чтобы построить массивы, представьте, что у нас есть личный лист данных клиентов в excel, и мы хотим построить массив для вывода информации о клиенте.

   Name -   Phone   -  Email  - Customer Number 
Person1 - 153486231 - [email protected] - 001
Person2 - 153486242 - [email protected] - 002
Person3 - 153486253 - [email protected] - 003
Person4 - 153486264 - [email protected] - 004
Person5 - 153486275 - [email protected] - 005

Мы будем динамически строить массив заголовков и массив Customers, заголовок будет содержать заголовки столбцов, а массив Customers будет содержать информацию каждого клиента / строки в виде массивов.

Dim Headers As Variant
' headers array with the top section of the customer data sheet
    For c = 1 To 4
        If IsEmpty(Headers) Then
            ReDim Headers(0)
            Headers(0) = Cells(1, c).Value
        Else
            ReDim Preserve Headers(0 To UBound(Headers) + 1)
            Headers(UBound(Headers)) = Cells(1, c).Value
        End If
    Next
    
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
    
    For r = 2 To 6
    'iterate through the customers/rows
        For c = 1 To 4
        'iterate through the values/columns
            
            'build array containing customer values
            If IsEmpty(Customer_Values) Then
                ReDim Customer_Values(0)
                Customer_Values(0) = Cells(r, c).Value
            ElseIf Customer_Values(0) = "" Then
                Customer_Values(0) = Cells(r, c).Value
            Else
                ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
                Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
            End If
        Next
        
        'add customer_values array to Customers Array
        If IsEmpty(Customers) Then
            ReDim Customers(0)
            Customers(0) = Customer_Values
        Else
            ReDim Preserve Customers(0 To UBound(Customers) + 1)
            Customers(UBound(Customers)) = Customer_Values
        End If
        
        'reset Custumer_Values to rebuild a new array if needed
        ReDim Customer_Values(0)
    Next

    Dim Main_Array(0 To 1) As Variant
    'main array will contain both the Headers and Customers
    
    Main_Array(0) = Headers
    Main_Array(1) = Customers

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

Результатом приведенного выше фрагмента является массив с чередованием с двумя массивами, один из тех массивов с 4 элементами, 2 уровня отступа, а другой сам по себе является другим массивом Jagged, содержащим 5 массивов из 4 элементов каждый и 3 уровня отступа, см. Ниже структуру:

Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
          (1) - Customers(0) - Array("Person1",153486231,"[email protected]",001)
                Customers(1) - Array("Person2",153486242,"[email protected]",002)
                ...
                Customers(4) - Array("Person5",153486275,"[email protected]",005)

Чтобы получить доступ к информации, которую вы должны иметь в виду о структуре созданного массива Jagged Array, в приведенном выше примере вы можете видеть, что Main Array содержит массив Headers и массив массивов ( Customers ), следовательно, с различными способами доступ к элементам.

Теперь мы прочитаем информацию о Main Array и распечатаем каждую из данных Клиентов в виде Info Type: Info .

For n = 0 To UBound(Main_Array(1))
    'n to iterate from fisrt to last array in Main_Array(1)
    
    For j = 0 To UBound(Main_Array(1)(n))
        'j will iterate from first to last element in each array of Main_Array(1)
        
        Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
        'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
        'we can call the header with j as the header array has the same structure as the customer array
    Next
Next

ЗАПОМНИТЕ, чтобы отслеживать структуру вашего Jagged Array, в приведенном выше примере для доступа к имени клиента, Main_Array -> Customers -> CustomerNumber -> Name к Main_Array -> Customers -> CustomerNumber -> Name который состоит из трех уровней, для возврата "Person4" вам понадобится расположение клиентов в Main_Array, затем местоположение клиента 4 в массиве Jagged Customers и, наконец, местоположение Main_Array(1)(3)(0) элемента в этом случае Main_Array(1)(3)(0) который является Main_Array(Customers)(CustomerNumber)(Name) .

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

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

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

Массив массива работает как матрица с различными уровнями, например, сравнение между одним, двумя и тремя измерениями.

Одно измерение — ваш типичный массив, он выглядит как список элементов.

Dim 1D(3) as Variant

*1D - Visually*
(0)
(1)
(2)

Два измерения будут выглядеть как сетка Sudoku или лист Excel, при инициализации массива вы определяете, сколько строк и столбцов будет иметь массив.

Dim 2D(3,3) as Variant
'this would result in a 3x3 grid 

*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

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

Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid

*3D - Visually*
       1st layer                 2nd layer                  3rd layer
         front                     middle                     back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)

Дальнейшие измерения можно рассматривать как умножение 3D, поэтому 4D (1,3,3,3) будет представлять собой два боковых боковых 3D-массива.


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

Создание

Пример ниже будет компиляцией списка сотрудников, каждый сотрудник будет иметь набор информации в списке (имя, фамилия, адрес, электронная почта, телефон …), пример, по существу, будет храниться в массиве ( сотрудник, информация), являющееся (0,0), является первым именем первого сотрудника.

Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want

Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements

Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements

For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
    For information_e = 0 To UBound(Employees, 2)
    'for each information element/column in the array
        
        Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
    Next
Next

Изменение размера

Изменение размера или ReDim Preserve Multi-Array, как и норма для массива One-Dimension, приведет к ошибке, вместо этого информация должна быть перенесена в массив Temporary с тем же размером, что и оригинал, плюс число добавляемых строк / столбцов. В приведенном ниже примере мы увидим, как инициализировать Temp Array, передать информацию из исходного массива, заполнить оставшиеся пустые элементы и заменить массив temp на исходный массив.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array

'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
        TempEmp(emp, info) = Employees(emp, info)
    
    Next
Next

'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray

For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
    For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
        
        TempEmp(emp, info) = InformationNeeded & "NewRow"
    
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp

Изменение значений элементов

Изменение / изменение значений в определенном элементе может быть выполнено путем простого вызова координаты для изменения и предоставления ей нового значения: Employees(0, 0) = "NewValue"

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

For emp = 0 To UBound(Employees)
    If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
    'if value found
        Employees(emp, 1) = "Married, Last Name Change"
        Exit For
        'don't iterate through a full array unless necessary
    End If
Next

Доступ к элементам в массиве может выполняться с помощью вложенного цикла (итерация каждого элемента), цикла и координат (итерации строк и доступа к столбцам напрямую) или прямого доступа к обеим координатам.

'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        Debug.Print Employees(emp, info)
    Next
Next

'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    Debug.Print Employees(emp, 0)
    Debug.Print Employees(emp, 1)
    Debug.Print Employees(emp, 2)
    Debug.Print Employees(emp, 3)
    Debug.Print Employees(emp, 4)
    Debug.Print Employees(emp, 5)
Next

'directly accessing element with coordinates
Debug.Print Employees(5, 5)

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


Трехмерный массив

Для 3D-массива мы будем использовать ту же предпосылку, что и 2D-массив, с добавлением не только хранения Employee и Information, но и построения, в котором они работают.

В трехмерном массиве будут присутствовать сотрудники (могут рассматриваться как строки), информация (столбцы) и здание, которые можно рассматривать как разные листы на документе excel, они имеют одинаковый размер между ними, но каждый лист имеет различный набор информации в своих ячейках / элементах. 3D-массив будет содержать n число 2D-массивов.

Создание

3D-массив нуждается в трех координатах для инициализации Dim 3Darray(2,5,5) As Variant первой координатой массива будет количество строений / таблиц (разные наборы строк и столбцов), вторая координата будет определять строки и третью Столбцы. В результате Dim выше будет создан трехмерный массив с 108 элементами ( 3*6*6 ), эффективно имеющий 3 разных набора 2D-массивов.

Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements

For building = 0 To UBound(ThreeDArray, 1)
    'for each building/set in the array
    For employee = 0 To UBound(ThreeDArray, 2)
    'for each employee/row in the array
        For information_e = 0 To UBound(ThreeDArray, 3)
        'for each information element/column in the array
            
            ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
        Next
    Next
Next

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

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

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array

'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
            TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
        
        Next
    Next
Next

'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
    For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
        For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
            
            TempEmp(building, emp, info) = InformationNeeded & "NewRow"
        
        Next
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp

Изменение значений элементов и чтение

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

Do
' using Do ... While for early exit
    For building = 0 To UBound(ThreeDArray, 1)
        For emp = 0 To UBound(ThreeDArray, 2)
            If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
            'if value found
                ThreeDArray(building, emp, 1) = "Married, Last Name Change"
                Exit Do
                'don't iterate through all the array unless necessary
            End If
        Next
    Next
Loop While False

'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            Debug.Print ThreeDArray(building, emp, info)
        Next
    Next
Next

'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        Debug.Print ThreeDArray(building, emp, 0)
        Debug.Print ThreeDArray(building, emp, 1)
        Debug.Print ThreeDArray(building, emp, 2)
        Debug.Print ThreeDArray(building, emp, 3)
        Debug.Print ThreeDArray(building, emp, 4)
        Debug.Print ThreeDArray(building, emp, 5)
    Next
Next

'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)

This post provides an in-depth look at the VBA array which is a very important part of the Excel VBA programming language. It covers everything you need to know about the VBA array.

We will start by seeing what exactly is the VBA Array is and why you need it.

Below you will see a quick reference guide to using the VBA Array.  Refer to it anytime you need a quick reminder of the VBA Array syntax.

The rest of the post provides the most complete guide you will find on the VBA array.

Related Links for the VBA Array

Loops are used for reading through the VBA Array:
For Loop
For Each Loop

Other data structures in VBA:
VBA Collection – Good when you want to keep inserting items as it automatically resizes.
VBA ArrayList – This has more functionality than the Collection.
VBA Dictionary – Allows storing a KeyValue pair. Very useful in many applications.

The Microsoft guide for VBA Arrays can be found here.

A Quick Guide to the VBA Array

Task Static Array Dynamic Array
Declare Dim arr(0 To 5) As Long Dim arr() As Long
Dim arr As Variant
Set Size See Declare above ReDim arr(0 To 5)As Variant
Get Size(number of items) See ArraySize function below. See ArraySize function below.
Increase size (keep existing data) Dynamic Only ReDim Preserve arr(0 To 6)
Set values arr(1) = 22 arr(1) = 22
Receive values total = arr(1) total = arr(1)
First position LBound(arr) LBound(arr)
Last position Ubound(arr) Ubound(arr)
Read all items(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
Read all items(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
Read all items Dim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Pass to Sub Sub MySub(ByRef arr() As String) Sub MySub(ByRef arr() As String)
Return from Function 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
Receive from Function Dynamic only Dim arr() As Long
Arr = GetArray()
Erase array Erase arr
*Resets all values to default
Erase arr
*Deletes array
String to array Dynamic only Dim arr As Variant
arr = Split(«James:Earl:Jones»,»:»)
Array to string Dim sName As String
sName = Join(arr, «:»)
Dim sName As String
sName = Join(arr, «:»)
Fill with values Dynamic only Dim arr As Variant
arr = Array(«John», «Hazel», «Fred»)
Range to Array Dynamic only Dim arr As Variant
arr = Range(«A1:D2»)
Array to Range Same as dynamic Dim arr As Variant
Range(«A5:D6») = arr

Download the Source Code and Data

Please click on the button below to get the fully documented source code for this article.

What is the VBA Array and Why do You Need It?

A VBA array is a type of variable. It is used to store lists of data of the same type. An example would be storing a list of countries or a list of weekly totals.

In VBA a normal variable can store only one value at a time.

In the following example we use a variable to store the marks of a student:

' Can only store 1 value at a time
Dim Student1 As Long
Student1 = 55

If we wish to store the marks of another student then we need to create a second variable.

In the following example, we have the marks of five students:

VBa Arrays

Student Marks

We are going to read these marks and write them to the Immediate Window.

Note: The function Debug.Print writes values to the Immediate  Window. To view this window select View->Immediate Window from the menu( Shortcut is Ctrl + G)

ImmediateWindow

ImmediateSampeText

As you can see in the following example we are writing the same code five times – once for each student:

' https://excelmacromastery.com/
Public Sub StudentMarks()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")
    
    ' Declare variable for each student
    Dim Student1 As Long
    Dim Student2 As Long
    Dim Student3 As Long
    Dim Student4 As Long
    Dim Student5 As Long

    ' Read student marks from cell
    Student1 = sh.Range("C" & 3).Value
    Student2 = sh.Range("C" & 4).Value
    Student3 = sh.Range("C" & 5).Value
    Student4 = sh.Range("C" & 6).Value
    Student5 = sh.Range("C" & 7).Value

    ' Print student marks
    Debug.Print "Students Marks"
    Debug.Print Student1
    Debug.Print Student2
    Debug.Print Student3
    Debug.Print Student4
    Debug.Print Student5

End Sub

The following is the output from the example:

VBA Arrays

Output

The problem with using one variable per student is that you need to add code for each student. Therefore if you had a thousand students in the above example you would need three thousand lines of code!

Luckily we have arrays to make our life easier. Arrays allow us to store a list of data items in one structure.

The following code shows the above student example using an array:

' ExcelMacroMastery.com
' https://excelmacromastery.com/excel-vba-array/
' Author: Paul Kelly
' Description: Reads marks to an Array and write
' the array to the Immediate Window(Ctrl + G)
' TO RUN: Click in the sub and press F5
Public Sub StudentMarksArr()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")

    ' Declare an array to hold marks for 5 students
    Dim Students(1 To 5) As Long

    ' Read student marks from cells C3:C7 into array
    ' Offset counts rows from cell C2.
    ' e.g. i=1 is C2 plus 1 row which is C3
    '      i=2 is C2 plus 2 rows which is C4
    Dim i As Long
    For i = 1 To 5
        Students(i) = sh.Range("C2").Offset(i).Value
    Next i

    ' Print student marks from the array to the Immediate Window
    Debug.Print "Students Marks"
    For i = LBound(Students) To UBound(Students)
        Debug.Print Students(i)
    Next i

End Sub

The advantage of this code is that it will work for any number of students. If we have to change this code to deal with 1000 students we only need to change the (1 To 5) to (1 To 1000) in the declaration. In the prior example we would need to add approximately five thousand lines of code.

Let’s have a quick comparison of variables and arrays. First we compare the declaration:

        ' Variable
        Dim Student As Long
        Dim Country As String

        ' Array
        Dim Students(1 To 3) As Long
        Dim Countries(1 To 3) As String

Next we compare assigning a value:

        ' assign value to variable
        Student1 = .Cells(1, 1) 

        ' assign value to first item in array
        Students(1) = .Cells(1, 1)

Finally we look at writing the values:

        ' Print variable value
        Debug.Print Student1

        ' Print value of first student in array
        Debug.Print Students(1)

As you can see, using variables and arrays is quite similar.

The fact that arrays use an index(also called a subscript) to access each item is important. It means we can easily access all the items in an array using a For Loop.

Now that you have some background on why arrays are useful let’s go through them step by step.

Two Types of VBA Arrays

There are two types of VBA arrays:

  1. Static – an array of fixed length.
  2. Dynamic(not to be confused with the Excel Dynamic Array) – an array where the length is set at run time.

The difference between these types is mostly in how they are created. Accessing values in both array types is exactly the same. In the following sections we will cover both of these types.

VBA Array Initialization

A static array is initialized as follows:

' https://excelmacromastery.com/
Public Sub DecArrayStatic()

    ' Create array with locations 0,1,2,3
    Dim arrMarks1(0 To 3) As Long

    ' Defaults as 0 to 3 i.e. locations 0,1,2,3
    Dim arrMarks2(3) As Long

    ' Create array with locations 1,2,3,4,5
    Dim arrMarks3(1 To 5) As Long

    ' Create array with locations 2,3,4 ' This is rarely used
    Dim arrMarks4(2 To 4) As Long

End Sub

VBA Arrays

An Array of 0 to 3

As you can see the length is specified when you declare a static array. The problem with this is that you can never be sure in advance the length you need. Each time you run the Macro you may have different length requirements.

If you do not use all the array locations then the resources are being wasted. So if you need more locations you can use ReDim but this is essentially creating a new static array.

The dynamic array does not have such problems. You do not specify the length when you declare it. Therefore you can then grow and shrink as required:

' https://excelmacromastery.com/
Public Sub DecArrayDynamic()

    ' Declare  dynamic array
    Dim arrMarks() As Long

    ' Set the length of the array when you are ready
    ReDim arrMarks(0 To 5)

End Sub

The dynamic array is not allocated until you use the ReDim statement. The advantage is you can wait until you know the number of items before setting the array length. With a static array you have to state the length upfront.

To give an example. Imagine you were reading worksheets of student marks. With a dynamic array you can count the students on the worksheet and set an array to that length. With a static array you must set the length to the largest possible number of students.

Assigning Values to VBA Array

To assign values to an array you use the number of the location. You assign the value for both array types the same way:

' https://excelmacromastery.com/
Public Sub AssignValue()

    ' Declare  array with locations 0,1,2,3
    Dim arrMarks(0 To 3) As Long

    ' Set the value of position 0
    arrMarks(0) = 5

    ' Set the value of position 3
    arrMarks(3) = 46

    ' This is an error as there is no location 4
    arrMarks(4) = 99

End Sub

VBA Array 2

The array with values assigned

The number of the location is called the subscript or index. The last line in the example will give a “Subscript out of Range” error as there is no location 4 in the array example.

VBA Array Length

There is no native function for getting the number of items in an array. I created the ArrayLength function below to return the number of items in any array no matter how many dimensions:

' https://excelmacromastery.com/
Function ArrayLength(arr As Variant) As Long

    On Error Goto eh
    
    ' Loop is used for multidimensional arrays. The Loop will terminate when a
    ' "Subscript out of Range" error occurs i.e. there are no more dimensions.
    Dim i As Long, length As Long
    length = 1
    
    ' Loop until no more dimensions
    Do While True
        i = i + 1
        ' If the array has no items then this line will throw an error
        Length = Length * (UBound(arr, i) - LBound(arr, i) + 1)
        ' Set ArrayLength here to avoid returing 1 for an empty array
        ArrayLength = Length
    Loop

Done:
    Exit Function
eh:
    If Err.Number = 13 Then ' Type Mismatch Error
        Err.Raise vbObjectError, "ArrayLength" _
            , "The argument passed to the ArrayLength function is not an array."
    End If
End Function

You can use it like this:

' Name: TEST_ArrayLength
' Author: Paul Kelly, ExcelMacroMastery.com
' Description: Tests the ArrayLength functions and writes
'              the results to the Immediate Window(Ctrl + G)
Sub TEST_ArrayLength()
    
    ' 0 items
    Dim arr1() As Long
    Debug.Print ArrayLength(arr1)
    
    ' 10 items
    Dim arr2(0 To 9) As Long
    Debug.Print ArrayLength(arr2)
    
    ' 18 items
    Dim arr3(0 To 5, 1 To 3) As Long
    Debug.Print ArrayLength(arr3)
    
    ' Option base 0: 144 items
    ' Option base 1: 50 items
    Dim arr4(1, 5, 5, 0 To 1) As Long
    Debug.Print ArrayLength(arr4)
    
End Sub

Using the Array and Split function

You can use the Array function to populate an array with a list of items. You must declare the array as a type Variant. The following code shows you how to use this function.

    Dim arr1 As Variant
    arr1 = Array("Orange", "Peach","Pear")

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

Arrays VBA

Contents of arr1 after using the Array function

The array created by the Array Function will start at index zero unless you use Option Base 1 at the top of your module. Then it will start at index one. In programming, it is generally considered poor practice to have your actual data in the code. However, sometimes it is useful when you need to test some code quickly.

The Split function is used to split a string into an array based on a delimiter. A delimiter is a character such as a comma or space that separates the items.

The following code will split the string into an array of four elements:

    Dim s As String
    s = "Red,Yellow,Green,Blue"

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

Arrays VBA

The array after using Split

The Split function is normally used when you read from a comma-separated file or another source that provides a list of items separated by the same character.

Using Loops With the VBA Array

Using a For Loop allows quick access to all items in an array. This is where the power of using arrays becomes apparent. We can read arrays with ten values or ten thousand values using the same few lines of code. There are two functions in VBA called LBound and UBound. These functions return the smallest and largest subscript in an array. In an array arrMarks(0 to 3) the LBound will return 0 and UBound will return 3.

The following example assigns random numbers to an array using a loop. It then prints out these numbers using a second loop.

' https://excelmacromastery.com/
Public Sub ArrayLoops()

    ' Declare  array
    Dim arrMarks(0 To 5) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' Print out the values in the array
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

The functions LBound and UBound are very useful. Using them means our loops will work correctly with any array length. The real benefit is that if the length of the array changes we do not have to change the code for printing the values. A loop will work for an array of any length as long as you use these functions.

Using the For Each Loop with the VBA Array

You can use the For Each loop with arrays. The important thing to keep in mind is that it is Read-Only. This means that you cannot change the value in the array.

In the following code the value of mark changes but it does not change the value in the array.

    For Each mark In arrMarks
        ' Will not change the array value
        mark = 5 * Rnd
    Next mark

The For Each is loop is fine to use for reading an array. It is neater to write especially for a Two-Dimensional array as we will see.

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

Using Erase with the VBA Array

The Erase function can be used on arrays but performs differently depending on the array type.

For a static Array the Erase function resets all the values to the default. If the array is made up of long integers(i.e type Long) then all the values are set to zero. If the array is of strings then all the strings are set to “” and so on.

For a Dynamic Array the Erase function DeAllocates memory. That is, it deletes the array. If you want to use it again you must use ReDim to Allocate memory.

Let’s have a look an example for the static array. This example is the same as the ArrayLoops example in the last section with one difference – we use Erase after setting the values. When the value are printed out they will all be zero:

' https://excelmacromastery.com/
Public Sub EraseStatic()

    ' Declare  array
    Dim arrMarks(0 To 3) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' ALL VALUES SET TO ZERO
    Erase arrMarks

    ' Print out the values - there are all now zero
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

We will now try the same example with a dynamic. After we use Erase all the locations in the array have been deleted. We need to use ReDim if we wish to use the array again.

If we try to access members of this array we will get a “Subscript out of Range” error:

' https://excelmacromastery.com/
Public Sub EraseDynamic()

    ' Declare  array
    Dim arrMarks() As Long
    ReDim arrMarks(0 To 3)

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' arrMarks is now deallocated. No locations exist.
    Erase arrMarks

End Sub

Increasing the length of the VBA Array

If we use ReDim on an existing array, then the array and its contents will be deleted.

In the following example, the second ReDim statement will create a completely new array. The original array and its contents will be deleted.

' https://excelmacromastery.com/
Sub UsingRedim()

    Dim arr() As String
    
    ' Set array to be slots 0 to 2
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    
    ' Array with apple is now deleted
    ReDim arr(0 To 3)

End Sub

If we want to extend the length of an array without losing the contents, we can use the Preserve keyword.

When we use Redim Preserve the new array must start at the same starting dimension e.g.

We cannot Preserve from (0 to 2) to (1 to 3) or to (2 to 10) as they are different starting dimensions.

In the following code we create an array using ReDim and then fill the array with types of fruit.

We then use Preserve to extend the length of the array so we don’t lose the original contents:

' https://excelmacromastery.com/
Sub UsingRedimPreserve()

    Dim arr() As String
    
    ' Set array to be slots 0 to 1
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    arr(1) = "Orange"
    arr(2) = "Pear"
    
    ' Reset the length and keep original contents
    ReDim Preserve arr(0 To 5)

End Sub

You can see from the screenshots below, that the original contents of the array have been “Preserved”.

VBA Preserve

Before ReDim Preserve

VBA Preserve

After ReDim Preserve

Word of Caution: In most cases, you shouldn’t need to resize an array like we have done in this section. If you are resizing an array multiple times then you may want to consider using a Collection.

Using Preserve with Two-Dimensional Arrays

Preserve only works with the upper bound of an array.

For example, if you have a two-dimensional array you can only preserve the second dimension as this example shows:

' https://excelmacromastery.com/
Sub Preserve2D()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' Change the length of the upper dimension
    ReDim Preserve arr(1 To 2, 1 To 10)

End Sub

If we try to use Preserve on a lower bound we will get the “Subscript out of range” error.

In the following code we use Preserve on the first dimension. Running this code will give the “Subscript out of range” error:

' https://excelmacromastery.com/
Sub Preserve2DError()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' "Subscript out of Range" error
    ReDim Preserve arr(1 To 5, 1 To 5)

End Sub

When we read from a range to an array, it automatically creates a two-dimensional array, even if we have only one column.

The same Preserve rules apply. We can only use Preserve on the upper bound as this example shows:

' https://excelmacromastery.com/
Sub Preserve2DRange()

    Dim arr As Variant
    
    ' Assign a range to an array
    arr = Sheet1.Range("A1:A5").Value
    
    ' Preserve will work on the upper bound only
    ReDim Preserve arr(1 To 5, 1 To 7)

End Sub

Sorting the VBA Array

There is no function in VBA for sorting an array. We can sort the worksheet cells but this could be slow if there is a lot of data.

The QuickSort function below can be used to sort an array.

' https://excelmacromastery.com/
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
    
        ' Swap values
        vTemp = arr(lTempLow)

        arr(lTempLow) = arr(lTempHi)
        arr(lTempHi) = vTemp
      
        ' Move to next positions
        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

You can use this function like this:

' https://excelmacromastery.com/
Sub TestSort()

    ' Create temp array
    Dim arr() As Variant
    arr = Array("Banana", "Melon", "Peach", "Plum", "Apple")
  
    ' Sort array
    QuickSort arr, LBound(arr), UBound(arr)

    ' Print arr to Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i

End Sub

Passing the VBA Array to a Sub

Sometimes you will need to pass an array to a procedure. You declare the parameter using parenthesis similar to how you declare a dynamic array.

Passing to the procedure using ByRef means you are passing a reference of the array. So if you change the array in the procedure it will be changed when you return.

Note: When you use an array as a parameter it cannot use ByVal, it must use ByRef. You can pass the array using ByVal making the parameter a variant.

' https://excelmacromastery.com/
' Passes array to a Function
Public Sub PassToProc()
    Dim arr(0 To 5) As String
    ' Pass the array to function
    UseArray arr
End Sub

Public Function UseArray(ByRef arr() As String)
    ' Use array
    Debug.Print UBound(arr)
End Function

Returning the VBA Array from a Function

It is important to keep the following in mind. If you want to change an existing array in a procedure then you should pass it as a parameter using ByRef(see last section). You do not need to return the array from the procedure.

The main reason for returning an array is when you use the procedure to create a new one. In this case you assign the return array to an array in the caller. This array cannot be already allocated. In other words you must use a dynamic array that has not been allocated.

The following examples show this

' https://excelmacromastery.com/
Public Sub TestArray()

    ' Declare dynamic array - not allocated
    Dim arr() As String
    ' Return new array
    arr = GetArray

End Sub

Public Function GetArray() As String()

    ' Create and allocate new array
    Dim arr(0 To 5) As String
    ' Return array
    GetArray = arr

End Function

Using a Two-Dimensional VBA Array

The arrays we have been looking at so far have been one-dimensional arrays. This means the arrays are one list of items.

A two-dimensional array is essentially a list of lists. If you think of a single spreadsheet row as a single dimension then more than one column is two dimensional. In fact a spreadsheet is the equivalent of a two-dimensional array. It has two dimensions – rows and columns.

One small thing to note is that Excel treats a one-dimensional array as a row if you write it to a spreadsheet. In other words, the array arr(1 to 5) is equivalent to arr(1 to 1, 1 to 5) when writing values to the spreadsheet.

The following image shows two groups of data. The first is a one-dimensional layout and the second is two dimensional.

VBA Array Dimension

To access an item in the first set of data(1 dimensional) all you need to do is give the row e.g. 1,2, 3 or 4.

For the second set of data (two-dimensional), you need to give the row AND the column. So you can think of 1 dimensional being multiple columns and one row and two-dimensional as being multiple rows and multiple columns.

Note: It is possible to have more than two dimensions in an array. It is rarely required. If you are solving a problem using a 3+ dimensional array then there probably is a better way to do it.

You declare a two-dimensional array as follows:

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

The following example creates a random value for each item in the array and the prints the values to the Immediate Window:

' https://excelmacromastery.com/
Public Sub TwoDimArray()

    ' Declare a two dimensional array
    Dim arrMarks(0 To 3, 0 To 2) As String

    ' Fill the array with text made up of i and j values
    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

    ' Print the values in the array to the Immediate Window
    Debug.Print "i", "j", "Value"
    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

You can see that we use a second For loop inside the first loop to access all the items.

The output of the example looks like this:

VBA Arrays

How this Macro works is as follows:

  • Enters the i loop
  • i is set to 0
  • Entersj loop
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • Exit j loop
  • i is set to 1
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • And so on until i=3 and j=2

You may notice that LBound and UBound have a second argument with the value 2. This specifies that it is the upper or lower bound of the second dimension. That is the start and end location for j. The default value 1 which is why we do not need to specify it for the i loop.

Using the For Each Loop

Using a For Each is neater to use when reading from an array.

Let’s take the code from above that writes out the two-dimensional array

    ' Using For loop needs two loops
    Debug.Print "i", "j", "Value"
    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

Now let’s rewrite it using a For each loop. You can see we only need one loop and so it is much easier to write:

    ' Using For Each requires only one loop
    Debug.Print "Value"
    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Using the For Each loop gives us the array in one order only – from LBound to UBound. Most of the time this is all you need.

Reading from a Range to the VBA Array

If you have read my previous post on Cells and Ranges then you will know that VBA has an extremely efficient way of reading from a Range of Cells to an Array and vice versa

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Declare dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from first row
    StudentMarks = Range("A1:Z1").Value

    ' Write the values back to the third row
    Range("A3:Z3").Value = StudentMarks

End Sub

The dynamic array created in this example will be a two dimensional array. As you can see we can read from an entire range of cells to an array in just one line.

The next example will read the sample student data below from C3:E6 of Sheet1 and print them to the Immediate Window:

' https://excelmacromastery.com/
Public Sub ReadAndDisplay()

    ' Get Range
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Sheet1").Range("C3:E6")

    ' Create dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from sheet1
    StudentMarks = rg.Value

    ' Print the array values
    Debug.Print "i", "j", "Value"
    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

Sample Student data

VBA 2D Array Output

Output from sample data

As you can see the first dimension(accessed using i) of the array is a row and the second is a column. To demonstrate this take a look at the value 44 in E4 of the sample data. This value is in row 2 column 3 of our data. You can see that 44 is stored in the array at StudentMarks(2,3).

You can see more about using arrays with ranges in this YouTube video

How To Make Your Macros Run at Super Speed

If your macros are running very slow then you may find this section very helpful. Especially if you are dealing with large amounts of data. The following is a very well-kept secret in VBA

Updating values in arrays is exponentially faster than updating values in cells.

In the last section, you saw how we can easily read from a group of cells to an array and vice versa. If we are updating a lot of values then we can do the following:

1. Copy the data from the cells to an array.
2. Change the data in the array.
3. Copy the updated data from the array back to the cells.

For example, the following code would be much faster than the code below it:

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Read values into array from first row
    Dim StudentMarks  As Variant
    StudentMarks = Range("A1:Z20000").Value

    Dim i As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        ' Update marks here
        StudentMarks(i, 1) = StudentMarks(i, 1) * 2
        '...
    Next i

    ' Write the new values back to the worksheet
    Range("A1:Z20000").Value = StudentMarks

End Sub
' https://excelmacromastery.com/
Sub UsingCellsToUpdate()
    
    Dim c As Variant
    For Each c In Range("A1:Z20000")
        c.Value = ' Update values here
    Next c
    
End Sub

Assigning from one set of cells to another is also much faster than using Copy and Paste:

' Assigning - this is faster
Range("A1:A10").Value = Range("B1:B10").Value

' Copy Paste - this is slower
Range("B1:B1").Copy Destination:=Range("A1:A10")

The following comments are from two readers who used arrays to speed up their macros

“A couple of my projects have gone from almost impossible and long to run into almost too easy and a reduction in time to run from 10:1.” – Dane

“One report I did took nearly 3 hours to run when accessing the cells directly — 5 minutes with arrays” – Jim

You can see more about the speed of Arrays compared to other methods in this YouTube video.

To see a comparison between Find, Match and Arrays it is worth checking out this post by Charles Williams.

Conclusion

The following is a summary of the main points of this post

  1. Arrays are an efficient way of storing a list of items of the same type.
  2. You can access an array item directly using the number of the location which is known as the subscript or index.
  3. The common error “Subscript out of Range” is caused by accessing a location that does not exist.
  4. There are two types of arrays: Static and Dynamic.
  5. Static is used when the length of the array is always the same.
  6. Dynamic arrays allow you to determine the length of an array at run time.
  7. LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
  8. The basic array is one dimensional. You can also have multidimensional arrays.
  9. You can only pass an array to a procedure using ByRef. You do this like this: ByRef arr() as long.
  10. You can return an array from a function but the array, it is assigned to, must not be currently allocated.
  11. A worksheet with its rows and columns is essentially a two-dimensional array.
  12. You can read directly from a worksheet range into a two-dimensional array in just one line of code.
  13. You can also write from a two-dimensional array to a range in just one line of code.

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  The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Indexes in Programming

“Index” is a common term used in all programming languages. It basically acts like a serial number of which an item or value can be referenced. For example, in the picture below, “Great Wall of China” is the 5th item in the series. In programming we say that its index is “5.” In some programming languages the index numbering starts with “0.” If such is the case, the index of the same “Great Wall of China” would be “4” (0, 1 , 2, 3, 4). 

In general, “index” can be used to reference the values of an array or a range (in Excel).

Index to reference the values of an array or a range in Excel.

The Index Formula in Excel

In MS Excel, index is a formula that helps us find the value in a specified array.

Syntax of the formula:

Index(< array name >, < row number >, [< col number>])

Where

  1. Array is an array of values (a list of one or more dimensions)/ a reference to an array.
  2. Row number is the row index being referred to
  3. Col number is the column index being referred to

Example 1

In this example we are trying to find the value in the 7th position of the lookup range (the parameter used in the formula).

Here the range is B2 to B9 i.e. Starting from the value “Taj Mahal” (position 1) in B2 until “Great Pyramid of Giza” (position 8) in B9. Visually we can see that Petra is the 7th value in the selected range. Hence, it is the value returned by the formula.

Note: S.no is given in the example for easy understanding and it has nothing to do with the Index formula.

Example of finding the value in the 7th position range.

Example 2

Let us try to find the price of the 7th item (“Sambar Idly”) sold at a snack bar. There are two columns here, one with the list of items and the other with the respective price. 

Note: Paste this table starting with cell A1 on the Excel sheet for the formula’s range to work.

Item Price
Ice cream 5
Sweet corn 6
Spinach Candy 8
Banana Cake 3
Peas Pulao 40
Methi Roti 30
Sambar Idly with ghee 20
Veg clear Soup 40
Masala Papad 10

The formula would be  =INDEX(A2:B10,7,2)

Where 

A2:B10 is the range of data in the table

7 because we are looking for the 7th item (row-wise)

2 because we want the price of the item. The price is in the 2nd col. And the answer would be 20.

The Index Function in VBA

The Index function in VBA is very simple. Just as in the formula, here we also have to pass the array and the position as parameters. The function then returns the value in that position.

Example 1

In the example below, there is an array of students in a class. Let us assume that we know the roll number of the student who has obtained Rank 1. We are asked to find his/her name.

Sub index_demo()

' declare variables
Dim arr_students()
Dim first_rank

' initialize the arrayarr_students = Array("John Capps", "Michel Pinny", "Kanya Dhan", "Ron Dincy", "Bella", "Mayur", "Jack finner", "Emi Thinner")

' We know that the fourth student in the array has got the first rank. We need to find his name
first_rank = Application.WorksheetFunction.Index(arr_students, 4)

'Display the name of the first rank holder in a messagebox
MsgBox first_rank &amp; " is the student who got the first rank."

End Sub

Example explained:

To start with, we have declared the required variables. Then we have initiated an array (arr_students) with the list of student names as values. 

In order to use the Index function, we should have the array and required position number as parameters. As we have created the array already (arr_students) and we know that the name of the student with the roll number “4” is to be fetched, we proceed to use the function.

Application.WorksheetFunction.Index (arr_students, 4)

Application refers to the Excel application being used currently.

Worksheetfunction refers to the bunch of functions offered by Excel for any worksheet.

Index is also a worksheetfunction which we are learning to use here.

The output/return value of this function is passed/caught in the variable declared earlier — first_rank.

Finally, the value of the variable is displayed with a description in a message box.

Microsoft Excel message box that reads "Ron Dincy is the student who got the first rank."

Example 2

In this example, we will use the worksheetfunction index in VBA but the array that we refer to will be a Range of Excel cells.

Scenario: Some sports personalities ran a race and reached the finish line in a particular order. The array of players is in the finishing order. We are asked to find the runner of the race.

Let’s try to find the person who wins the second place in the competition. This will be our position value in the function.

The range of the array is Range(“B2:B9”).

Knowing the required values, we can proceed with writing the code.

Sub index_demo2()

' declare variables
Dim arr_players()
Dim runner
' initialize the array
arr_players = Range("B2:C9")

' We know that the second player in the array is the runner. We need to find his name
runner = Application.WorksheetFunction.Index(arr_players, 2)

'Display the name of the runner in a messagebox
MsgBox runner(1) &amp; " is the player who won the second place. His email id is " &amp; runner(2)

End Sub 

Excel sheet with a message box pop-up that says "Fred is the player who won the second place."

Code explained:

As mentioned in Example 1, we have declared and initialized the variables. Then we use the Index function to find runner (2nd place) of the match. 

The flow of the program is the same with the difference that here we have been forced to use runner(1) to display value. 

Reason: An Excel range is considered a multidimensional array. Because of this, the return value is not just a string. Instead, it is also an array. To find a value in that array, we have to specify index. 

(1) is used here since there is only one value (or we have specified only 1 column in the range).
To understand it better, if we had used the range Range (“B2:C9” ) in our code, then the return value of the index would have both values in Range (“B2”) and Range(“C2”) i.e. All values of (various columns) of the second row (position parameter given in the Index function).

Example of the range specification.

The image above clearly shows the value of the runner object (the returned value). It has both the name and the email address. Suppose, I want to display the email address of the runner, I will have to display runner(2) in the messagebox.

MsgBox runner(1) &amp; " is the player who won the second place. His email id is " &amp; runner(2)

&lt;!-- /wp:shortcode --&gt;

&lt;!-- wp:image {"id":14452,"sizeSlug":"large","linkDestination":"none"} --&gt;
&lt;figure class="wp-block-image size-large"&gt;&lt;img src="https://software-solutions-online.com/wp-content/uploads/2021/06/unnamed-11.png" alt="Excel message box that reads &amp;quot;Fred is the player who won the second place. His email id is [email protected]&amp;quot;" class="wp-image-14452"/&gt;&lt;/figure&gt;
&lt;!-- /wp:image --&gt;

&lt;!-- wp:heading {"level":3} --&gt;
&lt;h3&gt;Example 3&lt;/h3&gt;
&lt;!-- /wp:heading --&gt;

&lt;!-- wp:paragraph --&gt;
&lt;p&gt;In the example below, we get the capital of a state whose index is known. So, we are using an array of two dimensions. If we use formula, we refer to the 4&lt;sup&gt;th&lt;/sup&gt; row and 2&lt;sup&gt;nd&lt;/sup&gt; column of the selected range. So the value of the cell turns out to be “Patna”.&lt;/p&gt;
&lt;!-- /wp:paragraph --&gt;

&lt;!-- wp:image {"id":14457,"sizeSlug":"large","linkDestination":"none"} --&gt;
&lt;figure class="wp-block-image size-large"&gt;&lt;img src="https://software-solutions-online.com/wp-content/uploads/2021/06/unnamed-12-1024x266.png" alt="Example of using array to find capital states." class="wp-image-14457"/&gt;&lt;/figure&gt;
&lt;!-- /wp:image --&gt;

&lt;!-- wp:paragraph --&gt;
&lt;p&gt;Let us do the same using VBA.&lt;/p&gt;
&lt;!-- /wp:paragraph --&gt;

&lt;!-- wp:shortcode --&gt;

Sub IndexMatch_demo1()

' declare variables
Dim required_pos, str_capital, arr_states_cap, capital_col

' initialize variables
required_pos = 4
capital_col = 2
arr_states_cap = Range("B2:C16")

'use the function to get the capital
str_capital = Application.WorksheetFunction.Index([arr_states_cap], required_pos, 2)

' display the result
MsgBox str_capital

End Sub

Code explained:

Post declaration and initialization of variables, the Index function is used to get the value  in the 4th row, 2nd column of the selected state, capital range of cells on the Excel sheet.

Finally, the output that we see in the message box would be “Patna” which is the capital of Bihar.

The Match Formula and Function 

Here is my article about the Match formula in Excel and Match function in VBA:

Using the Match Function in VBA and Excel – VBA and VB.Net Tutorials, Education and Programming Services (software-solutions-online.com)

Using the Index Function with the Match Function

As we have already understood, the Index function gives the value in the known index of an array. The Match function does the opposite. It provides the index value of an item in an array or range of values.

It is possible to use one of these functions within the other. i.e. Match within Index (or) Index within Match.

Example 1

Here is a table that has details of States, Capitals and another column to describe when it was formed (“Founded on”). We are asked to find the “Founded on” value of the state “Maharashtra”.

Let us assume that we do not know its index. So, initially we will use the Match function to find its index.

Once we get that index, using Index we can get the respective values of that index (rows) against all columns.

Example of using a Match function to find an index.

Sub IndexMatch_demo()

'declare variables
Dim strstate, arr_states, arr_capitals, arr_founded, rowposition_state, str_capital, str_founded

' initialize variables ( set values for them )
strstate = "Maharashtra"
arr_states = Range("B2:B30")
arr_capitals = Range("C2:C30")
arr_founded = Range("D2:D30")

' find the position of the state in the first array ( 0 here states an exact match)
rowposition_state = Application.WorksheetFunction.Match(strstate, ([arr_states]), 0)

'Find the respective capital and "founded on" values of the said state.
str_capital = Application.WorksheetFunction.Index([arr_capitals], rowposition_state)
str_founded = Application.WorksheetFunction.Index([arr_founded], rowposition_state)

' display all values
Debug.Print str_capital(1)
Debug.Print str_founded(1)

End Sub

Code explained:

The required variables are first declared and then initialized. From these lines, we infer that we are supposed to find the capital and “Founded on” values of  the state “Maharashtra.” So, using the Match function in VBA, we find the position of  the state ”Maharashtra.” Then using the same value as the index, we find the capital and “Founded on” values from the respective arrays and display the same in the Immediate window (using the debug.print statement).

In order to explain this further, three arrays were created in the example. If the ranges quoted for each of these arrays are not within the same range ( row values), then this concept of using the same index (row num here) for finding values in other arrays will not work.  So, let us redo the same with one range as a subset of another range to understand the concept better.

Sub IndexMatch_demo3()

'declare variables
Dim strstate, arr_states, start_pos, end_pos, rowposition_state, str_capital, arr_states_captials

' initialize variables ( set values for them )
strstate = "Maharashtra"
start_pos = 2
end_pos = 30

'dynamic defining of the arrays from the excel sheet. The rows values are not hardcoded here.
arr_states_captials = Range("B" &amp; start_pos &amp; ":D" &amp; end_pos)
arr_states = Range("B" &amp; start_pos &amp; ":B" &amp; end_pos)

' find the position of the state in the states array ( 0 here states an exact match)
rowposition_state = Application.WorksheetFunction.Match(strstate, [arr_states], 0)

'Find the respective capital and "founded on" values of the said state.
str_capital = Application.WorksheetFunction.Index([arr_states_captials], rowposition_state, 2)
str_founded = Application.WorksheetFunction.Index([arr_states_captials], rowposition_state, 3)

' display all values
Debug.Print str_capital
Debug.Print str_founded

End Sub

Code explained:

The difference in this modified code lies in the dynamic building of array range. A single dimensional array is defined in order to find the index using the Match function. Then we find the respective values from the other two columns. The Index function here uses both the row position and col position parameter since the array is multidimensional (a complete picture of this is available in the image above).

Conclusion

In my experience, I see that the Index function can be used with multidimensional arrays but when it comes to the Match function, multidimensional arrays have to be sliced using loops and conditions before being passed as parameters. Using a combination of both these functions (Index and Match), it is possible and easy to point to any value/index/any target in a table or an array or a range of Excel cells. Using them wisely can produce great results.

Declaring an Array in VBA

Declaring an array is very similar to declaring a variable, except you need to declare the dimension of the Array right after its name:

Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings

By default, Arrays in VBA are indexed from ZERO, thus, the number inside the parenthesis doesn’t refer to the size of the array, but rather to the index of the last element

Accessing Elements

Accessing an element of the Array is done by using the name of the Array, followed by the index of the element, inside parenthesis:

myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"

Array Indexing

You can change Arrays indexing by placing this line at the top of a module:

Option Base 1

With this line, all Arrays declared in the module will be indexed from ONE.

Specific Index

You can also declare each Array with its own index by using the To keyword, and the lower and upper bound (= index):

Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24

Dynamic Declaration

When you do not know the size of your Array prior to its declaration, you can use the dynamic declaration, and the ReDim keyword:

Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements

Note that using the ReDim keyword will wipe out any previous content of your Array. To prevent this, you can use the Preserve keyword after ReDim:

Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"

ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element

Use of Split to create an array from a string

Split Function

returns a zero-based, one dimensional array containing a specified number of substrings.

Syntax

Split(expression [, delimiter [, limit [, compare]]])

Part Description
expression Required. String expression containing substrings and delimiters. If expression is a zero-length string(«» or vbNullString), Split returns an empty array containing no elements and no data. In this case, the returned array will have a LBound of 0 and a UBound of -1.
delimiter Optional. String character used to identify substring limits. If omitted, the space character (» «) is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant Value Description
Description -1 Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database.

Example

In this example it is demonstrated how Split works by showing several styles. The comments will show the result set for each of the different performed Split options. Finally it is demonstrated how to loop over the returned string array.

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

    textArray = Split("172.23.56.4", ".")
    'Result: {"172", "23", "56", "4"}

    textArray = Split("A;B;C;D", ";")
    'Result: {"A", "B", "C", "D"}

    textArray = Split("A;B;C;D", ";", 1)
    'Result: {"A;B;C;D"}

    textArray = Split("A;B;C;D", ";", 2)
    'Result: {"A", "B;C;D"}

    textArray = Split("A;B;C;D", ";", 3)
    'Result: {"A", "B", "C;D"}

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

Iterating elements of an array

For…Next

Using the iterator variable as the index number is the fastest way to iterate the elements of an array:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

Nested loops can be used to iterate multi-dimensional arrays:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

For Each…Next

A For Each...Next loop can also be used to iterate arrays, if performance doesn’t matter:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

A For Each loop will iterate all dimensions from outer to inner (the same order as the elements are laid out in memory), so there is no need for nested loops:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

Note that For Each loops are best used to iterate Collection objects, if performance matters.


All 4 snippets above produce the same output:

 0
 1
 2
 3

Dynamic Arrays (Array Resizing and Dynamic Handling)

Dynamic Arrays

Adding and reducing variables on an array dynamically is a huge advantage for when the information you are treating does not have a set number of variables.

Adding Values Dynamically

You can simply resize the Array with the ReDim Statement, this will resize the array but to if you which to retain the information already stored in the array you’ll need the part Preserve.

In the example below we create an array and increase it by one more variable in each iteration while preserving the values already in the array.

Dim Dynamic_array As Variant
' first we set Dynamic_array as variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        'isempty() will check if we need to add the first value to the array or subsequent ones
    
        ReDim Dynamic_array(0)
        'ReDim Dynamic_array(0) will resize the array to one variable only
        Dynamic_array(0) = n

    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
        Dynamic_array(UBound(Dynamic_array)) = n
        'attribute a value to the last variable of Dynamic_array
    End If

Next

Removing Values Dynamically

We can utilise the same logic to to decrease the the array. In the example the value «last» will be removed from the array.

Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
    
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value

Resetting an Array and Reusing Dynamically

We can as well re-utilise the arrays we create as not to have many on memory, which would make the run time slower. This is useful for arrays of various sizes.
One snippet you could use to re-utilise the array is to ReDim the array back to (0), attribute one variable to to the array and freely increase the array again.

In the snippet below I construct an array with the values 1 to 40, empty the array, and refill the array with values 40 to 100, all this done dynamically.

Dim Dynamic_array As Variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        ReDim Dynamic_array(0)
        Dynamic_array(0) = n
    
    ElseIf Dynamic_array(0) = "" Then
        'if first variant is empty ( = "") then give it the value of n
        Dynamic_array(0) = n
    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        Dynamic_array(UBound(Dynamic_array)) = n
    End If
    If n = 40 Then
        ReDim Dynamic_array(0)
        'Resizing the array back to one variable without Preserving,
        'leaving the first value of the array empty
    End If

Next

Jagged Arrays (Arrays of Arrays)

Jagged Arrays NOT Multidimensional Arrays

Arrays of Arrays(Jagged Arrays) are not the same as Multidimensional Arrays if you think about them visually Multidimensional Arrays would look like Matrices (Rectangular) with defined number of elements on their dimensions(inside arrays), while Jagged array would be like a yearly calendar with the inside arrays having different number of elements, like days in on different months.

Although Jagged Arrays are quite messy and tricky to use due to their nested levels and don’t have much type safety, but they are very flexible, allow you to manipulate different types of data quite easily, and don’t need to contain unused or empty elements.

Creating a Jagged Array

In the below example we will initialise a jagged array containing two arrays one for Names and another for Numbers, and then accessing one element of each

Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements

Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")

OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside

Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element

Dynamically Creating and Reading Jagged Arrays

We can as well be more dynamic in our approx to construct the arrays, imagine that we have a customer data sheet in excel and we want to construct an array to output the customer details.

   Name -   Phone   -  Email  - Customer Number 
Person1 - 153486231 - [email protected] - 001
Person2 - 153486242 - [email protected] - 002
Person3 - 153486253 - [email protected] - 003
Person4 - 153486264 - [email protected] - 004
Person5 - 153486275 - [email protected] - 005

We will Dynamically construct an Header array and a Customers array, the Header will contain the column titles and the Customers array will contain the information of each customer/row as arrays.

Dim Headers As Variant
' headers array with the top section of the customer data sheet
    For c = 1 To 4
        If IsEmpty(Headers) Then
            ReDim Headers(0)
            Headers(0) = Cells(1, c).Value
        Else
            ReDim Preserve Headers(0 To UBound(Headers) + 1)
            Headers(UBound(Headers)) = Cells(1, c).Value
        End If
    Next
    
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
    
    For r = 2 To 6
    'iterate through the customers/rows
        For c = 1 To 4
        'iterate through the values/columns
            
            'build array containing customer values
            If IsEmpty(Customer_Values) Then
                ReDim Customer_Values(0)
                Customer_Values(0) = Cells(r, c).Value
            ElseIf Customer_Values(0) = "" Then
                Customer_Values(0) = Cells(r, c).Value
            Else
                ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
                Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
            End If
        Next
        
        'add customer_values array to Customers Array
        If IsEmpty(Customers) Then
            ReDim Customers(0)
            Customers(0) = Customer_Values
        Else
            ReDim Preserve Customers(0 To UBound(Customers) + 1)
            Customers(UBound(Customers)) = Customer_Values
        End If
        
        'reset Custumer_Values to rebuild a new array if needed
        ReDim Customer_Values(0)
    Next

    Dim Main_Array(0 To 1) As Variant
    'main array will contain both the Headers and Customers
    
    Main_Array(0) = Headers
    Main_Array(1) = Customers

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

The Result of the above snippet is an Jagged Array with two arrays one of those arrays with 4 elements, 2 indention levels, and the other being itself another Jagged Array containing 5 arrays of 4 elements each and 3 indention levels, see below the structure:

Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
          (1) - Customers(0) - Array("Person1",153486231,"[email protected]",001)
                Customers(1) - Array("Person2",153486242,"[email protected]",002)
                ...
                Customers(4) - Array("Person5",153486275,"[email protected]",005)

To access the information you’ll have to bear in mind the structure of the Jagged Array you create, in the above example you can see that the Main Array contains an Array of Headers and an Array of Arrays (Customers) hence with different ways of accessing the elements.

Now we’ll read the information of the Main Array and print out each of the Customers information as Info Type: Info.

For n = 0 To UBound(Main_Array(1))
    'n to iterate from fisrt to last array in Main_Array(1)
    
    For j = 0 To UBound(Main_Array(1)(n))
        'j will iterate from first to last element in each array of Main_Array(1)
        
        Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
        'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
        'we can call the header with j as the header array has the same structure as the customer array
    Next
Next

REMEMBER to keep track of the structure of your Jagged Array, in the example above to access the Name of a customer is by accessing Main_Array -> Customers -> CustomerNumber -> Name which is three levels, to return "Person4" you’ll need the location of Customers in the Main_Array, then the Location of customer four on the Customers Jagged array and lastly the location of the element you need, in this case Main_Array(1)(3)(0) which is Main_Array(Customers)(CustomerNumber)(Name).

Multidimensional Arrays

Multidimensional Arrays

As the name indicates, multi dimensional arrays are arrays that contain more than one dimension, usually two or three but it can have up to 32 dimensions.

A multi array works like a matrix with various levels, take in example a comparison between one, two, and three Dimensions.

One Dimension is your typical array, it looks like a list of elements.

Dim 1D(3) as Variant

*1D - Visually*
(0)
(1)
(2)

Two Dimensions would look like a Sudoku Grid or an Excel sheet, when initializing the array you would define how many rows and columns the array would have.

Dim 2D(3,3) as Variant
'this would result in a 3x3 grid 

*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

Three Dimensions would start to look like Rubik’s Cube, when initializing the array you would define rows and columns and layers/depths the array would have.

Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid

*3D - Visually*
       1st layer                 2nd layer                  3rd layer
         front                     middle                     back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)

Further dimensions could be thought as the multiplication of the 3D, so a 4D(1,3,3,3) would be two side-by-side 3D arrays.


Two-Dimension Array

Creating

The example below will be a compilation of a list of employees, each employee will have a set of information on the list (First Name, Surname, Address, Email, Phone …), the example will essentially be storing on the array (employee,information) being the (0,0) is the first employee’s first name.

Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want

Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements

Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements

For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
    For information_e = 0 To UBound(Employees, 2)
    'for each information element/column in the array
        
        Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
    Next
Next

Resizing

Resizing or ReDim Preserve a Multi-Array like the norm for a One-Dimension array would get an error, instead the information needs to be transferred into a Temporary array with the same size as the original plus the number of row/columns to add. In the example below we’ll see how to initialize a Temp Array, transfer the information over from the original array, fill the remaining empty elements, and replace the temp array by the original array.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array

'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
        TempEmp(emp, info) = Employees(emp, info)
    
    Next
Next

'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray

For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
    For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
        
        TempEmp(emp, info) = InformationNeeded & "NewRow"
    
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp

Changing Element Values

To change/alter the values in a certain element can be done by simply calling the coordinate to change and giving it a new value:
Employees(0, 0) = "NewValue"

Alternatively iterate through the coordinates use conditions to match values corresponding to the parameters needed:

For emp = 0 To UBound(Employees)
    If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
    'if value found
        Employees(emp, 1) = "Married, Last Name Change"
        Exit For
        'don't iterate through a full array unless necessary
    End If
Next

Accessing the elements in the array can be done with a Nested Loop (iterating every element), Loop and Coordinate (iterate Rows and accessing columns directly), or accessing directly with both coordinates.

'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        Debug.Print Employees(emp, info)
    Next
Next

'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    Debug.Print Employees(emp, 0)
    Debug.Print Employees(emp, 1)
    Debug.Print Employees(emp, 2)
    Debug.Print Employees(emp, 3)
    Debug.Print Employees(emp, 4)
    Debug.Print Employees(emp, 5)
Next

'directly accessing element with coordinates
Debug.Print Employees(5, 5)

Remember, it’s always handy to keep an array map when using Multidimensional arrays, they can easily become confusion.


Three-Dimension Array

For the 3D array, we’ll use the same premise as the 2D array, with the addition of not only storing the Employee and Information but as well Building they work in.

The 3D array will have the Employees (can be thought of as Rows), the Information (Columns), and Building that can be thought of as different sheets on an excel document, they have the same size between them, but every sheets has a different set of information in its cells/elements. The 3D array will contain n number of 2D arrays.

Creating

A 3D array needs 3 coordinates to be initialized Dim 3Darray(2,5,5) As Variant the first coordinate on the array will be the number of Building/Sheets (different sets of rows and columns), second coordinate will define Rows and third Columns. The Dim above will result in a 3D array with 108 elements (3*6*6), effectively having 3 different sets of 2D arrays.

Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements

For building = 0 To UBound(ThreeDArray, 1)
    'for each building/set in the array
    For employee = 0 To UBound(ThreeDArray, 2)
    'for each employee/row in the array
        For information_e = 0 To UBound(ThreeDArray, 3)
        'for each information element/column in the array
            
            ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
        Next
    Next
Next

Resizing a 3D array is similar to resizing a 2D, first create a Temporary array with the same size of the original adding one in the coordinate of the parameter to increase, the first coordinate will increase the number of sets in the array, the second and third coordinates will increase the number of Rows or Columns in each set.

The example below increases the number of Rows in each set by one, and fills those recently added elements with new information.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array

'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
            TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
        
        Next
    Next
Next

'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
    For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
        For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
            
            TempEmp(building, emp, info) = InformationNeeded & "NewRow"
        
        Next
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp

Changing Element Values and Reading

Reading and changing the elements on the 3D array can be done similarly to the way we do the 2D array, just adjust for the extra level in the loops and coordinates.

Do
' using Do ... While for early exit
    For building = 0 To UBound(ThreeDArray, 1)
        For emp = 0 To UBound(ThreeDArray, 2)
            If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
            'if value found
                ThreeDArray(building, emp, 1) = "Married, Last Name Change"
                Exit Do
                'don't iterate through all the array unless necessary
            End If
        Next
    Next
Loop While False

'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            Debug.Print ThreeDArray(building, emp, info)
        Next
    Next
Next

'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        Debug.Print ThreeDArray(building, emp, 0)
        Debug.Print ThreeDArray(building, emp, 1)
        Debug.Print ThreeDArray(building, emp, 2)
        Debug.Print ThreeDArray(building, emp, 3)
        Debug.Print ThreeDArray(building, emp, 4)
        Debug.Print ThreeDArray(building, emp, 5)
    Next
Next

'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)

Dim pos, arr, val

arr=Array(1,2,4,5)
val = 4

pos=Application.Match(val, arr, False)

if not iserror(pos) then
   Msgbox val & " is at position " & pos
else
   Msgbox val & " not found!"
end if

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

Dim arr(1 To 10, 1 To 2)
Dim x

For x = 1 To 10
    arr(x, 1) = x
    arr(x, 2) = 11 - x
Next x

Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)

EDIT: стоит ли здесь упомянуть то, что @ARich указал в комментариях — использование Index() для среза массива имеет ужасную производительность, если вы делаете это в цикле.

При тестировании (код ниже) подход Index() почти в 2000 раз медленнее, чем использование вложенного цикла.

Sub PerfTest()

    Const VAL_TO_FIND As String = "R1800:C8"
    Dim a(1 To 2000, 1 To 10)
    Dim r As Long, c As Long, t

    For r = 1 To 2000
        For c = 1 To 10
            a(r, c) = "R" & r & ":C" & c
        Next c
    Next r

    t = Timer
    Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
    ' >> 0.00781 sec

     t = Timer
    Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
    ' >> 14.18 sec

End Sub

Function FindLoop(arr, val) As Boolean
    Dim r As Long, c As Long
    For r = 1 To UBound(arr, 1)
    For c = 1 To UBound(arr, 2)
        If arr(r, c) = val Then
            FindLoop = True
            Exit Function
        End If
    Next c
    Next r
End Function

Function FindIndex(arr, val)
    Dim r As Long
    For r = 1 To UBound(arr, 1)
        If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
            FindIndex = True
            Exit Function
        End If
    Next r
End Function

Понравилась статья? Поделить с друзьями:
  • Excel vba array filter
  • Excel vba array add
  • Excel vba argument not optional что это
  • Excel vba applies to
  • Excel tutorial for beginners