Redim 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!

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

VBA ReDim

Excel VBA ReDim

We can adjust the number of elements in an array through VBA Redim. Redim is not a function, it is Dynamic memory allocation program through Redim statement. When we do use Redim, a specific amount of memory is kept aside to store the data.

How to Use VBA ReDim Statement?

We will discuss how to use VBA ReDim Statement by using some examples.

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

VBA ReDim – Example #1

When we use Dim for an array, we cannot change the value of data store in an array. But when we use Redim, we can change the stored value in an array. This process of changing the array is called re-dimensioning the array.

Suppose we have an array A of 4 cell value then it will be defined with;

  • Dim A(3) As Double

VBA ReDim Array 1

As we can see all the cells has “0” as stored value. Now suppose if we Redim the Dim A with 3 cell data and store the value in it then it will look like as below.

  • ReDim B(2) As Double

B(0) = 1; B(1) = 3, B(2) = -6

VBA ReDim Array 2

It will look like as;

Now if we want to add cells in it, we can do it. Then it will automatically assign the “0” to that cells. Now for implementing ReDim, press Alt + F11 to open VBA Window. And from the Insert menu select Module option to open a new window as shown below.

Insert Module

Now open Subcategory and add any name. As we are using ReDim so we have named as UsingReDim.

Code:

Sub UsingReDim()

End Sub

VBA ReDim Example 1-1

Now before defining ReDim, first define any Integer. Here we have defined it as “A” with array length 3. And store some values in a created array of 3 cells as shown below.

Code:

Sub UsingReDim()

Dim A(2) As Integer

ReDim A(2)

A(0) = 1
A(1) = 2
A(2) = 3

End Sub

VBA ReDim Example 1-2

Now printing the values stored in Integer A we need to create message box with the help of command MsgBox as shown below.

Code:

Sub UsingReDim()

Dim A(2) As Integer 

A(0) = 1
A(1) = 2
A(2) = 3

MsgBox A(0)
MsgBox A(1)
MsgBox A(2)

End Sub

VBA ReDim Example 1-3

Now run the code by clicking on the play button or F5 key as shown below.

VBA ReDim Example 1-4

Now we will use ReDim and it will store more than defined characters in the array. For this use ReDim for defined Integer A. Firstly, we will remove the defined cell count from Dim. The use of Redim function is as follows:

  • ReDim A(2) is used for A(0), A(1), A(2) cells array.
  • ReDim A(4) is used for A(0), A(1), A(2), A(3), A(4) cells with two extra dummy cells.

Code:

Sub UsingReDim()

Dim A() As Integer 

ReDim A(2)

A(0) = 1
A(1) = 2
A(2) = 3

ReDim A(4)

MsgBox A(0)
MsgBox A(1)
MsgBox A(2)

End Sub

VBA ReDim Example 1-5

Once done then run the complete code by clicking on the play button or using F5 key. Once we run the complete code, we will 3 message boxes but with a message containing only “0” as shown below.

Example 1-6

Which is because ReDim actually has only 3 values but it did not carry stored values under defined integers. Using Redim only does not store any values and carry forward the previously stored values into it. To apply the same we need to preserve the values of defined integer A, with the help of ReDim. By using Preserve in VBA, we can store the value in ReDim. For this, we will add Preserve after ReDim in VBA Codeas shown below.

Code:

Sub UsingReDim()

Dim A() As Integer 

ReDim A(2)

A(0) = 1
A(1) = 2
A(2) = 3

ReDim Preserve A(4)

MsgBox A(0)
MsgBox A(1)
MsgBox A(2)

End Sub

VBA ReDim Example 1-7

Now run the complete code again. We will see 3 message boxes with all the stored values in it as show below. Example 1-8

Now, you must be wondering why we used A(4) with ReDim Preserve?

Below is the explanation of it. Where 1st, 2nd and 3rd position of array is occupied with values 1, 2 and 3 respectively. And 4th and 5th position which represents 3 and 4 count of array A are dummy cells. Which means, if there is not data stored 4th and 5th position then it will automatically consider the value “0” and message will not get populated.

If we try to see the values stored in 4th and 5th position of ReDim array, then we need to insert a message box for these 2 positions as well.

Code:

Sub UsingReDim()

Dim A() As Integer

ReDim A(3)

A(0) = 1
A(1) = 2
A(2) = 3

ReDim Preserve A(4)

MsgBox A(0)
MsgBox A(1)
MsgBox A(2)
MsgBox A(3)
MsgBox A(4)

End Sub

 Example 1-9

As we have added message boxed for 4th and 5th position without storing any value. Now run the code again.

Example 1-10

As we can see in the above screenshots, for a 4th and 5th position we got message boxes but the value is showing as”0”. Which means explains the above statement. If there is no value defined then ReDim Preserve will automatically consider and fill “0” in the rest of the cells.

VBA ReDim – Example #2

Now let’s see how to use ReDim Statement with String instead of Integer.

Code:

Sub UsingReDim()

Dim A() As String 

ReDim A(3)

A(0) = "Customer"
A(1) = "Product"
A(2) = "Product Id"

ReDim Preserve A(4)

MsgBox A(0)
MsgBox A(1)
MsgBox A(2)
MsgBox A(3)
MsgBox A(4)

End Sub

Example 2-1

Once done, then run the complete code using F5 key or manually as shown below. Example 2-2

As we can see in the above screenshot we are getting all the defined and stored characters in first 3 message boxes. And in 4th and 5th box we are getting nothing. As ReDim stores no value if not defined. For Integers it will reflect as “0” but with String, it will show only blank messages.

Pros Of Excel VBA ReDim

  • VBA ReDim allows us to redefine the dimension values.
  • We can define as many as dimensional arrays with no or zero value and store the values later.
  • ReDim meaning Re-Dimensioning gives use the allowances of adding any numbers of data arrays without increasing the size of stored data.

Things To Remember

  • Always remember to add Preserve after ReDim in VBA, so that it will store the previously used dimensions.
  • If a dimension is defined as String, then any position left blank in assigning values, will carry blank and once we print the same with the help of message box will give blank message box as well.
  • If we have defined the dimensions Dim with 3 characters or cell values, then in ReDim we can use any number of dimensions carrying already defined and stored values in Dim.

Recommended Articles

This has been a guide to Excel VBA ReDim. Here we discussed how to use VBA ReDim Statement to remove spaces along with some practical examples and downloadable excel template. You can also go through our other suggested articles–

  1. VBA On Error
  2. VBA Number Format
  3. VBA Find
  4. VBA TRIM

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