Redim arrays in vba excel

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

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

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

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

Public Massiv1(9) As Integer

Dim Massiv2(1 To 9) As String

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

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

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

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

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

Public Massiv1(3, 6) As Integer

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

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

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

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

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

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

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

Public Massiv1() As Integer

Dim Massiv2() As String

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

Public Massiv1() As Integer

Dim Massiv2() As String

ReDim Massiv1(1 To 20)

ReDim Massiv2(3, 5, 4)

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

Dim Massiv1() as Variant, x As Integer

x = 20

ReDim Massiv1(1 To x)

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

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

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

Dim Massiv1() As String

операторы

ReDim Massiv1(5, 2, 3)

операторы

ReDim Preserve Massiv1(5, 2, 7)

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

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

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

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

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

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

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

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

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

Функция Array

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

Sub Test1()

Dim a() As Variant

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

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

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

End Sub

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

Функция LBound

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

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

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

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

Функция UBound

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

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

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

Sub Test2()

Dim a(2 To 53) As String

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

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

End Sub

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

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

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

Sub Test3()

Dim a() As Variant, i As Long

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

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

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

    Next

End Sub

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

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

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

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

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

операторы

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

ReDim Massiv2(2, 5, 3)

операторы

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

Erase Massiv1

Erase Massiv2

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

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

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

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

Dim Massiv() As Double

операторы

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

ReDim Massiv(5, 6, 8)

операторы

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

ReDim Massiv(5, 6, 8)


Return to VBA Code Examples

In this Article

  • Dynamic Array
    • Dynamic Variant Arrays
  • Redim vs. Redim Preserve
    • Using ReDim
    • Using ReDim Preserve

This tutorial will demonstrate how to use dynamic arrays (redim and redim preserve) in VBA.

Dynamic Array

Dynamic Arrays are arrays that can change sizes (as opposed to static arrays, which are static).

To declare a dynamic array, you declare the array, but omit the array size:

Dim strNames() As String

Then, before you can assign values to your array, you must use the ReDim Statement to set the array to your desired size:

ReDim strNames(1 to 3)

Now, anytime you want to change your array size, simply use ReDim (or ReDim Preserve as we’ll learn about below).

Dynamic Variant Arrays

Note: Variant Arrays are a little different. With variant arrays, you don’t need to set the array size with ReDim before assigning values.

Sub TestArray()
'declare the variable
    Dim varNames() As Variant
'populate the array
    varNames() = Array("Fred", "Wilma", "Barney", "Betty")
'return the values
    MsgBox Join(varNames, ",")
End Sub

Redim vs. Redim Preserve

The ReDim statement resizes an array, clearing all existing values.

The ReDim Preserve statement resizes an array, keeping (“preserving”) all existing values.

Using ReDim

In practice, resizing an array with ReDim looks like this:

Sub TestReDim()
'declare the string array
   Dim strNames() As String
'resize the string array to be able to hold 3 values
   ReDim strNames(1 to 3)
'populate the array with 3 names
   strNames(1) = "Mel"
   strNames(2) = "Steve"
   strNames(3) = "Bob"
'show the result in the immediate window
   Debug.Print Join(strNames, vbCrLf)
End Sub

vba redim output 1

Using ReDim Preserve

In this example, we will use ReDim to set the initial dynamic array and then ReDim Preserve to resize the array, keeping the original values:

Sub TestReDim()
'declare the string array
   Dim strNames() As String
'resize the string array to be able to hold 3 values
   ReDim strNames(1 to 3)
'populate the array
   strNames(1) = "Mel"
   strNames(2) = "Steve"
   strNames(3) = "Bob"
'show the result in the immediate window
   Debug.Print Join(strNames, vbCrLf)
'redim but preseve the data
   ReDim Preserve strNames(1 to 4)
   strNames(4) = "Fred"
'show the result in the immediate window
   Debug.Print Join(strNames, vbCrLf)
End Sub

vba redim output 2

If you do not use the PRESERVE statement, you would lose the data that had been in the array previously.

vba redim output 3

In the  immediate window above, the array populated Mel, Steve and Bob.  When it was re-declared, it remove those values and instead returned 3 blank values and then the value ‘Fred’.   This is due to the PRESERVE statement being omitted.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA ReDim Array

Excel VBA ReDim Array

In this article, we will see an outline on the Excel VBA ReDim Array. Normally when we give declare an array we provide a size to the array for the number of elements the array can hold, such type of arrays are known as static arrays. Then there is a different type of array where we do not provide the size of the array and such types of arrays are known as dynamic arrays. But the question arises that once the size of the array has been defined can we change the size of the array again? The answer is yes we can again change the size of the array once it is defined by using the ReDim statement. Thus making it a dynamic array. However, there are some limitations to its users using the ReDim statement alone such as the value stored in the previous array is lost and the new value is stored. Now let us see the mechanism of this ReDim statement with some examples.

How to Use ReDim Array in Excel VBA?

The following examples will teach us how to use ReDim Array in Excel by using the VBA Code.

You can download this VBA ReDim Array — Excel Template here – VBA ReDim Array — Excel Template

Example #1

For the first example, we will see how do we use the ReDim statement in the VBA.

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Once the module is inserted we can see it in the project on the left-hand side.

Code:

Sub Example1()

End Sub

VBA ReDim Array Example1-2

Step 3: Declare an array as an integer data type.

Code:

Sub Example1()

Dim A() As Integer

End Sub

Integer Data Type Example1-3

Step 4: Now let us change the dimension of the array using the ReDim statement assign the array with some values.

Code:

Sub Example1()

Dim A() As Integer
ReDim A(2)
A(0) = 2
A(1) = 1
A(2) = 3

End Sub

Dimension Example1-4

Step 5: For the sake of this example let us see what does the value A(2) has and then we resize the array by ReDim statement to A(3) and then again we will see the value of A(2).

Code:

Sub Example1()

Dim A() As Integer
ReDim A(2)
A(0) = 2
A(1) = 1
A(2) = 3
MsgBox A(2)
ReDim A(3)
MsgBox A(2)

End Sub

Resize Example 1-5

Step 6: When we execute the above code we will first see the result of the first array.

Msgbox Example 1-6

When we press OK we should again get a result of three i.e. the same result supposedly.

Msgbox Example1-7

The value turns to 0 because the previous array has lost its value.

Example #2

Let us make a real-life example where we will use ReDim statement to count the number of the last row filled in the column. At first, we will start with this example where we will change the size of the array and in the next example, we will see what happens if we use the preserve statement with the ReDim statement. For this, follow the below steps:

Step 1: For this example declare another subprocedure.

Code:

Sub Example2()

End Sub

Subprocedure Example 2-1

Step 2: Now declare an array and two variables as an integer, note to not give dimension to the array.

Code:

Sub Example2()

Dim numbers() As Integer, size As Integer, i As Integer

End Sub

VBA ReDim Array Example 2-2

Step 3: Now let us calculate the size of the array and store the size in the variable named size.

Code:

Sub Example2()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))

End Sub

VBA ReDim Array Example2-3

Step 4: Once we have the size of the array now we can resize the array using the ReDim keyword.

Code:

Sub Example2()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))
ReDim numbers(size)

End Sub

VBA ReDim Array Example 2-4

Step 5: Now let us loop through the array to initialize each element.

Code:

Sub Example2()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))
ReDim numbers(size)
For i = 1 To size
numbers(i) = Cells(i, 1).Value
Next i

End Sub

VBA ReDim Array Example2-5

Step 6: Now let us display the last element in the array with the Msgbox function.

Code:

Sub Example2()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))
ReDim numbers(size)
For i = 1 To size
numbers(i) = Cells(i, 1).Value
Next i
MsgBox numbers(size)

End Sub

VBA ReDim Array Example 2-6

Step 7: Before running the code, let us see what we have in column A of sheet 2.

VBA ReDim Array Example2-7

Step 8: Now we can run the code.

VBA ReDim Array Example2-8

Example #3

In addition to the above example when we resized the array with the number of values in the column. What if we again resize the array and then check a specific value in the array. For this, follow the below steps:

Step 1: We will again use the ReDim statement after the last line of the code.

Code:

Sub Example3()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))
ReDim numbers(size)
For i = 1 To size
numbers(i) = Cells(i, 1).Value
Next i
MsgBox numbers(size)
ReDim numbers(3)

End Sub

VBA ReDim Array Example3-1

Step 2: Now we can check what is the value in numbers(1).

Code:

Sub Example3()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(2).Columns(1))
ReDim numbers(size)
For i = 1 To size
numbers(i) = Cells(i, 1).Value
Next i
MsgBox numbers(size)
ReDim numbers(3)
MsgBox numbers(1)

End Sub

VBA ReDim Array Example3-2

Step 3: Run the code by hitting the F5 or Run button.

VBA ReDim Array Example3-3

This value was expected to let us see another value.

VBA ReDim Array Example3-4

It should be 2 but we got 0 because the previous value is lost.

Step 4: Now let us use the preserve statement after the REDIM keyword,

Code:

Sub Example3()

Dim numbers() As Integer, size As Integer, i As Integer
size = WorksheetFunction.CountA(Worksheets(1).Columns(1))
ReDim numbers(size)
For i = 1 To size
numbers(i) = Cells(i, 1).Value
Next i
MsgBox numbers(size)
ReDim Preserve numbers(3)
MsgBox numbers(1)

End Sub

VBA ReDim Array Example3-5

Step 5: Now when we run the code by hitting the F5 or Run button. we will get the desired result.

VBA ReDim Array Example3-3

VBA ReDim Array Example3-7

When we press OK we will see the following.

Explanation:

ReDim is a statement or a keyword used to resize the array as we saw in the above examples. To resize an array we must keep this in mind that the array must be dynamic and must not have a dimension at the declaration.

Things to Remember

There are a few things we need to remember about ReDim:

  • ReDim statement is used after the declaration of the array.
  • ReDim statement does not store the previous array values.
  • To store the previous values we need to use the preserve keyword.
  • The array must not have dimensions at the time of declaration.

Recommended Articles

This is a guide to the VBA ReDim Array. Here we discuss how to use ReDim Array in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA SendKeys
  2. VBA CInt
  3. VBA SubString
  4. VBA Dynamic Array

Excel VBA ReDim Statement

The VBA ReDim statement is similar to the Dim statement. But, the difference is that one may use it to store or allocate more storage space or decrease the storage space a variable or an array has. Now, there are two important aspects used with the statement: Preserve. If one uses Preserve with this statement, it creates a new array with different sizes. But, on the other hand, if one does not use Preserve with this statement, it just changes the array size of the current variable.

Arrays are an important part of VBA coding. Using arrays, we can store more than one value in the same variable we defined. Like how we declare the variable using the word “Dim,” we need to declare the array name by using “Dim” as well.

To declare the array name, we need first to identify the kind of array we are going to define. In arrays, we have 5 types:

  1. Static Array
  2. Dynamic Array
  3. One Dimensional Array
  4. Two Dimensional Array
  5. Multi-Dimensional Array

In the static array in excelArray formulas are extremely helpful and powerful formulas that are used in Excel to execute some of the most complex calculations. There are two types of array formulas: one that returns a single result and the other that returns multiple results.read more, we will decide the lower value and upper value of the array well in advance while declaring the variable. For example, look at the below example.

Code:

Sub ReDim_Example1()
  
  Dim MyArray(1 To 5) As String

End Sub

MyArray is the array’s name, which can hold the value from 1 to 5. So, for example, MyArray can hold 5 different results, like the one below.

Code:

Sub ReDim_Example1()
  Dim MyArray(1 To 5) As String

  MyArray(1) = "Hi"
  MyArray(2) = "Good"
  MyArray(3) = "Morning"
  MyArray(4) = "Have a"
  MyArray(5) = "Nice Day"

End Sub
Table of contents
  • Excel VBA ReDim Statement
    • Dynamic Array with ReDim Statement
    • Examples to use VBA Redim Statement
      • Example #1
      • Example #2 – Resize the Array Size While Remembering the Old Values.
    • Things to Remember Here
    • Recommended Articles

Dynamic Array with ReDim Statement

But in the dynamic array, this is not the case. Therefore, we will not decide on the lower and upper values well in advance. Rather, we define the array name and assign data type.

Sub ReDim_Example1()

Dim MyArray() As String

End Sub

To make the array name dynamic, we need to declare it with the word “Dim” first, but don’t decide the array size well in advance. Instead, we name an array with empty values inside the parenthesis (). When the array does not include size, it treats it as a dynamic array.

Dim MyArray() As String

When you mention the array size inside the parenthesis, it becomes a static array. Dim MyArray(1 to 5) As String.

In the dynamic array, we always resize the array size by using the word “ReDim” in the next line of the code.

ReDim MyArray(1 to 6) As String

Any value stored to the array name in the previous steps, i.e., using the “Dim” statement, stands null, and the size we declared using “ReDim” becomes the new size of the array.

Examples to use VBA Redim Statement

You can download this VBA ReDim Excel Template here – VBA ReDim Excel Template

Example #1

Look at the example of using the “ReDim” statement practically. Then, follow the below steps to apply “ReDim.”

Step 1: Create a macro name first.

Step 2: Declare an array name as a string.

Code:

Sub ReDim_Example1()

  Dim MyArray() As String

End Sub

Example 1

Step 3: Now, use “Redim” and assign the array size.

Code:

Sub ReDim_Example1()

  Dim MyArray() As String
  ReDim MyArray(1 To 3)

End Sub

Redim VBA Example 1-1

Step 4: The array name “MyArray” can hold up to 3 values here. Assign the value to these 3 arrays like the below one.

Code:

Sub ReDim_Example1()

  Dim MyArray() As String
  ReDim MyArray(1 To 3)

  MyArray(1) = "Welcome"
  MyArray(2) = "to"
  MyArray(3) = "VBA"

End Sub

Redim VBA Example 1-2

So, the first array is equal to the word “Welcome,” and the second is equal to the word “to.” Finally, the third array is equal to the word “VBA.”

Step 5: Now, store these array values in cells.

Code:

Sub ReDim_Example1()

  Dim MyArray() As String
  ReDim MyArray(1 To 3)

  MyArray(1) = "Welcome"
  MyArray(2) = "to"
  MyArray(3) = "VBA"

  Range("A1").Value = MyArray(1)
  Range("B1").Value = MyArray(2)
  Range("C1").Value = MyArray(3)

End Sub

Example 1-3

Step 6: If you run this code, we should have these values in A1, B1, and C1 cells, respectively.

Redim Visual basic Application Example 1-4

Example #2 – Resize the Array Size While Remembering the Old Values.

Once the array name is assigned values, we can resize it at any point in the procedure by using the word “ReDim Preserve.”

Assume you have already declared an array name and assigned values to those array names like the below one.

Now, you would like to increase the array length by 2, i.e., 5. In this case, we can use the word VBA “ReDim Preserve” to resize the array length and remember the old values.

Code:

Sub ReDim_Example2()
  
  Dim MyArray() As String
  ReDim MyArray(3)

  MyArray(1) = "Welcome"
  MyArray(2) = "to"
  MyArray(3) = "VBA"

  ReDim Preserve MyArray(4)
  MyArray(4) = "Character 1"

  Range("A1").Value = MyArray(1)
  Range("B1").Value = MyArray(2)
  Range("C1").Value = MyArray(3)
  Range("D1").Value = MyArray(4)

End Sub

Now, we can assign two more values to the array.

Code:

Sub ReDim_Example2()

  Dim MyArray() As String
  ReDim MyArray(3)

  MyArray(1) = "Welcome"
  MyArray(2) = "to"
  MyArray(3) = "VBA"

  ReDim Preserve MyArray(4)
  MyArray(4) = "Character 1"

  Range("A1").Value = MyArray(1)
  Range("B1").Value = MyArray(2)
  Range("C1").Value = MyArray(3)
  Range("D1").Value = MyArray(4)

End Sub

Now, store these values in cells.

Code:

Sub ReDim_Example2()

  Dim MyArray() As String
  ReDim MyArray(3)

  MyArray(1) = "Welcome"
  MyArray(2) = "to"
  MyArray(3) = "VBA"

  ReDim Preserve MyArray(4)
  MyArray(4) = "Character 1"

  Range("A1").Value = MyArray(1)
  Range("B1").Value = MyArray(2)
  Range("C1").Value = MyArray(3)
  Range("D1").Value = MyArray(4)

End Sub

Now, run the Macro and see what happens.

ReDim Preserve 1

So, we got the new word in the D1 cell.

We need to use the word “Preserve” because the array should remember the old array values in the procedure.

When you ignore the word “Preserve,” it will not remember old values.

Things to Remember Here

  • The ReDim can only hold the last value of the array, not the many values. So, for example, we cannot use the code “ReDim Preserve MyArray(4 to 5)”. Instead, it will throw an error.
  • We cannot ReDim static arrays. When you assign the array size inside the parenthesis, it becomes a static array.
  • Using ReDim, we cannot change the data type. The array can hold whatever data type we have assigned while declaring the array.

Recommended Articles

This article has been a guide to VBA ReDim. Here, we discuss handling dynamic arrays using ReDim Preserve, examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA ISNULL
  • VBA Format
  • Delete Row in VBA
  • Excel VBA Subscript Out of Range
  • VBA Max

The Excel VBA ReDim statement initializes and resizes a dynamic VBA Array. Be sure to check the difference between Fixed VBA Arrays and Dynamic VBA Arrays.

ReDim [Preserve] varname ( subscripts ) 

Parameters

Preserve
Optional. Keyword to be used if you want to resize your array and keep all items intact.
varname
The name of the array variable.
subscripts
The subscripts of the array defining either it’s upper bounds or lower and upper bounds. See examples below.

Using ReDim with single dimension arrays

Below an example of sizing and resizing a VBA Array:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2) 'Sizing array to upper bound 2. Array size is 3 -> 0 to 2
arr(2) = 10
Debug.Print arr(2) 'Result: 10

ReDim arr(1 to 2) 'Resizing array to size 2 -> 1 to 2. All items will be empty again.
Debug.Print array(2) 'Result: Empty

Using ReDim to resize an array but preserving its contents

Below an example of sizing and resizing a VBA Array, but keeping its contents preserved:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2) 'Sizing array to upper bound 2. Array size is 3 -> 0 to 2
arr(2) = 10
Debug.Print arr(2) 'Result: 10

ReDim Preserve arr(1 to 2) 'Resizing array to size 2 -> 1 to 2. All items will be Preserved as keyword was used.
Debug.Print array(2) 'Result: 10. Hurray!

Using ReDim with multidimensional arrays

Below an example of sizing and resizing a multidimensional array:

Dim arr() As Variant 'declaration of variant array
ReDim arr(2, 2)
arr(1, 1) = 10
    
ReDim Preserve arr(2, 10)
Debug.Print arr(1, 1) 'Result: 10

Понравилась статья? Поделить с друзьями:
  • Reading more than one word at a time
  • Reddit what is this word
  • Rearrange the letters to form a word
  • Reading mode in word
  • Red underlining in word