Vba excel redim что такое

Массивы в 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!

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

ReDim statement (VBA)

vblr6.chm1008999

vblr6.chm1008999

office

5044cb55-6cdc-16a7-6558-dcff7ab4b933

06/27/2019

medium

Used at the procedure level to reallocate storage space for dynamic array variables.

Syntax

ReDim [ Preserve ] varname ( subscripts ) [ As type ], [ varname ( subscripts ) [ As type ]] . . .

The ReDim statement syntax has these parts:

Part Description
Preserve Optional. Keyword used to preserve the data in an existing array when you change the size of the last dimension.
varname Required. Name of the variable; follows standard variable naming conventions.
subscripts Required. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

[lower To] upper [ , [lower To] upper ] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement. The lower bound is zero if no Option Base statement is present.

type Optional. Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String (for variable-length strings), String length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.

Use a separate As type clause for each variable being defined. For a Variant containing an array, type describes the type of each element of the array, but doesn’t change the Variant to some other type.

Remarks

The ReDim statement is used to size or resize a dynamic array that has already been formally declared by using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).

Use the ReDim statement repeatedly to change the number of elements and dimensions in an array. However, you can’t declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant. If the array is contained in a Variant, the type of the elements can be changed by using an As type clause, unless you are using the Preserve keyword, in which case, no changes of data type are permitted.

If you use the Preserve keyword, you can resize only the last array dimension and you can’t change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.

The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10) 
. . . 
ReDim Preserve X(10, 10, 15) 

Similarly, when you use Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error.

If you make an array smaller than it was, data in the eliminated elements will be lost.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string («»), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.

A variable that refers to an object must be assigned an existing object by using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn’t refer to any particular instance of an object.

The ReDim statement acts as a declarative statement if the variable it declares doesn’t exist at the module level or procedure level. If another variable with the same name is created later, even in a wider scope, ReDim will refer to the later variable and won’t necessarily cause a compilation error, even if Option Explicit is in effect. To avoid such conflicts, ReDim should not be used as a declarative statement, but simply for redimensioning arrays.

[!NOTE]
To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.

Example

This example uses the ReDim statement to allocate and reallocate storage space for dynamic-array variables. It assumes the Option Base is 1.

Dim MyArray() As Integer ' Declare dynamic array. 
Redim MyArray(5) ' Allocate 5 elements. 
For I = 1 To 5 ' Loop 5 times. 
 MyArray(I) = I ' Initialize array. 
Next I 

The next statement resizes the array and erases the elements.

Redim MyArray(10) ' Resize to 10 elements. 
For I = 1 To 10 ' Loop 10 times. 
 MyArray(I) = I ' Initialize array. 
Next I 

The following statement resizes the array but does not erase elements.

Redim Preserve MyArray(15) ' Resize to 15 elements. 

See also

  • Data types
  • Statements

[!includeSupport and feedback]

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

Понравилась статья? Поделить с друзьями:
  • Vba excel sheets names
  • Vba excel redim preserve subscript out of range
  • Vba excel sheets item
  • Vba excel recordset свойства
  • Vba excel sheets by name