Example
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 - 1@STACK - 001
Person2 - 153486242 - 2@STACK - 002
Person3 - 153486253 - 3@STACK - 003
Person4 - 153486264 - 4@STACK - 004
Person5 - 153486275 - 5@STACK - 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,"1@STACK",001)
Customers(1) - Array("Person2",153486242,"2@STACK",002)
...
Customers(4) - Array("Person5",153486275,"5@STACK",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)
.
I’ve got a 3-dimensional array, call it Arr(25,10,10), where I want to copy all contents of a given first index to another first index, e.g. Arr(6,-,-) to Arr(17,-,-). I’d like to do this without using For..Next loops every time. I think what I need is to change the array structure so it becomes a 1-dimensional array (Arr(25)) having a 2-dimensional array (Arr2(10,10)) as its elements, but I’m not sure how to do that. How do I Dim the array and how do I copy one index to another? Any help appreciated.
asked Oct 5, 2019 at 22:46
4
If you want to restructure your array you can do something like this:
Sub Tester()
Dim arr(25)
Dim i As Long
For i = 0 To 25
Dim a(10, 10)
arr(i) = a
Next i
arr(6)(1, 1) = 99
arr(17)(1, 1) = 88
arr(17) = arr(6)
Debug.Print arr(17)(1, 1) '>> 99
End Sub
answered Oct 6, 2019 at 3:20
Tim WilliamsTim Williams
150k8 gold badges96 silver badges124 bronze badges
This uses a Type to define the two-D array, and then packs it within the 1-D array
Option Explicit
Type Ta2D
a2D(1 To 10, 1 To 10)
End Type
Sub ArraySlicing_take3()
Dim a1D(1 To 25) As Ta2D
'Populate a sample 3-D array with values...
Dim x, y, z
For z = 1 To 25
For y = 1 To 10
For x = 1 To 10
a1D(z).a2D(y, x) = "D" & z & "R" & y & ":C" & x
Next x
Next y
Next z
'...done setting up sample array
Dim w(1) As Ta2D
w(1) = a1D(6)
a1D(17) = w(1)
End Sub
‘
answered Oct 6, 2019 at 3:30
donPablodonPablo
1,9371 gold badge13 silver badges18 bronze badges
Getting Started with Arrays in Visual Basic for Applications
A good overview over arrays in VBA can be found in the MSDN. It covers the basics pretty well (with code examples), e.g.
— what arrays are and why you’d need them,
— how to create arrays and resize dynamic arrays,
— it talks about the differences between arrays and variants containing arrays,
— how to assign one array to another,
— how to return an array from a function or pass arrays to a procedure,
and much more…
There’re a couple of VBA code examples for working with arrays and how to use arrays to work with values from an Excel worksheet.
There’s also a post with examples about using arrays to work with Excel cell values and performance considerations in this journal.
Now, with the basics covered, there’re a few more things about arrays to keep in mind:
- You can’t define constant arrays. If you need an array of constants, you’ll have to use a variable array, fill it at runtime, and take care that you don’t change it later on.
- The declaration
Dim myArray(10) As Integer
is allowed, but you should better use
Dim myArray(1 To 10) As Integer
It makes the code easier to understand, and you can be sure about the lower boundary and not have to rely on the default setting (
Option Base
) being what you expect it to be (0 or 1). The same applies forReDim
. - Arrays as parameters are always passed
ByRef
, which means only a pointer to the array will be passed to the function/procedure, not the array itself. If you change the array in the procedure, the changes will be visible in the calling program.If you insist on passing an array by value, use
Run "Procedurename", Parameter1, Parameter2, ...
Since
Run
automatically converts all arguments into values, changes to the array in the called procedure won’t affect the original array. - You can get the lower boundary of an array with the function
LBound(myArray, dimension)
and the upper boundary with the function
UBound(myArray, dimension)
dimension
is the number of the dimension you want to know, with 1 being the first dimension and so on. For a one-dimensional array, you don’t need to specify the 1. - Looping over all elements of an array with:
For Each myElement In myArray
mySum = mySum + myElement
Nextis usually faster than
For i = LBound(myArray) To UBound(myArray)
mySum = mySum + myArray(i)
NextAnd you have the advantage that you don’t have to worry what exactly the lower and upper boundaries of the array are.
But theFor Each
variant only works for reading array elements! If you changemyElement
, the corresponding element in the array stays untouched.myElement
must be of data typeVariant
, no matter of what data type the array elements are. - You can check whether a variable of data type
Variant
contains an array with
Useful Functions for Working with Arrays in VBA
The Array
function is an easy way to create and fill an array with values. Pass all values as parameters to the function, and it’ll return a one-dimensional array with these values as elements, in the same order as they were passed to the function. The first element has always the index 0, independent from any Option Base
settings.
Sub TestArray()
Dim myArray() As Variant
'create array from list of comma separated strings
myArray = Array("One", "Two", "Three")
'display array elements
MsgBox myArray(0) & vbCr & myArray(1) & vbCr & myArray(2)
'this also works with numbers as arguments
myArray = Array(10, 20, 30)
'display array elements
MsgBox myArray(0) & vbCr & myArray(1) & vbCr & myArray(2)
End Sub
The Array
function always returns an array of data type Variant
, but the data type of the elements can differ. It depends on the type of value which is passed to the function.
For example,
would return an array with the first element being of data type String
. The second element is of data type Integer
and the last element is of data type Double
.
If you pass nothing to the Array
function, it’ll return an empty array. In this case, the upper boundary of the array is -1, smaller than the lower boundary, which is always 0.
For example,
would return -1.
If you don’t have all values separately, but rather a list of values in one string, you can use the Split
function to separate them and create a one-dimensional array of strings. Again, the resulting array always begins with index 0.
You can specify the delimiter that separates the values in the string, e.g. comma or semicolon. If you don’t specify a delimiter, the string will be split by the spaces.
If you pass an empty string to the Split
function, it’ll return an empty array. Like with the array function, the returned array has an upper boundary of -1 if it is empty.
You won’t get an empty array when you pass a string to the Split
function that doesn’t contain the delimiter. In this case the returned array contains one element, which is the string itself.
The reverse of Split
is the Join
function. It takes an array of strings and returns one string containing all elements from the array. You can specify a delimiter, which will be added between each value.
If you pass an empty array to the Join
function, it’ll return an empty string.
Sub TestSplitJoin()
Dim myStr As String
Dim myArray() As String
'string with values, delimited by comma
myStr = "A1,B2,C3"
'split string into array of substrings
myArray = Split(myStr, ",")
'display array elements
MsgBox myArray(0) & vbCr & myArray(1) & vbCr & myArray(2)
'concatenate all elements of array into one string,
'with " and " connecting them
myStr = Join(myArray, " and ")
'display string
MsgBox myStr
End Sub
If you want to check if a certain item exists in an array of strings, you could loop over all items and compare them with your match string. But you can also use the Filter
function for this.
Filter(myArray, myMatch, myInclude)
takes myArray
and compares each of its elements with the string in myMatch
. Depending on myInclude
being True
(Default) or False
, it’ll return an array containing all elements of myArray
that contain myMatch
, or don’t contain it.
The search is case sensitive, so if myMatch
is a lower case letter, it won’t find elements which contain this letter in upper case and vice versa.
Since the function returns a new array with the found elements, you don’t get the indexes of the elements in the searched array. The function only tells you whether elements exist that contain/don’t contain the match string, and which, but not where.
If no matching elements were found, the Filter
function returns an array containing no elements, and the upper boundary of that array is -1.
Another limitation of the Filter
function is that you can’t tell it to look for exact matches only. It’ll always return all (or none of the) elements that include the match string, in other words, it does Like
comparisons, not checks for equality.
The function always compares strings, so if you filter a numeric array, it’ll convert the numbers to strings and then check them. And because it doesn’t look for exact matches only, a search for a number will return not only elements equal to the match, but also elements, which contain this number as a part, e.g.
Filter(Array(1, 10, 210), 1)
will return all elements of the array because each number has 1 in it.
A few examples to test the Filter
function:
Sub TestFilter() Dim myArray() As Variant Dim myFilteredArray As Variant 'create array myArray = Array("One", "Two", "Three") 'filter array for elements containing "T" myFilteredArray = Filter(myArray, "T", True) 'show result MsgBox "Filtering Array(""One"", ""Two"", ""Three"") " & _ "for elements with ""T"" returned" & _ vbCr & Join(myFilteredArray, vbCr) 'filter array for elements not containing "T" myFilteredArray = Filter(myArray, "T", False) 'show result MsgBox "Filtering Array(""One"", ""Two"", ""Three"") " & _ "for elements without ""T"" returned" & _ vbCr & Join(myFilteredArray, vbCr) 'filter array for elements containing "t" myFilteredArray = Filter(myArray, "t", True) 'show result MsgBox "Filtering Array(""One"", ""Two"", ""Three"") " & _ "for elements with ""t"" returned" & _ vbCr & Join(myFilteredArray, vbCr) 'filter numeric array for "1" myArray = Array(1, 2, 3, 10) myFilteredArray = Filter(myArray, 1) 'show result MsgBox "Filtering numeric Array(1, 2, 3, 10) " & _ "for elements with 1 returned" & _ vbCr & Join(myFilteredArray, vbCr) End Sub
The following code is an example how to get only elements that match exactly:
Sub FilterExactly() Const myMarker As String = "!" Const myDelimiter As String = "," Dim myArray() As Variant Dim mySearchArray As Variant Dim myFilteredArray As Variant 'create array myArray = Array(1, 2, 3, 10) 'pre-filter the array for elements containing 1 myFilteredArray = Filter(myArray, 1) If UBound(myFilteredArray) > -1 Then 'mark the beginning and end of each found element 'myMarker and myDelimiter must be characters that 'don't occur in any element of the array! mySearchArray = Split(myMarker & Join(myFilteredArray, myMarker & _ myDelimiter & myMarker) & myMarker, myDelimiter) 'now filter modified array, include markers in search myFilteredArray = Filter(mySearchArray, _ myMarker & "1" & myMarker) 'remove markers from result myFilteredArray = Split(Replace(Join(myFilteredArray, _ myDelimiter), myMarker, ""), myDelimiter) End If 'show result MsgBox "Filtering Array(" & Join(myArray, ", ") & _ ") for exact matches with 1 returned:" & _ vbCr & Join(myFilteredArray, vbCr) End Sub
Multidimensional Arrays vs. Arrays of Arrays
If an array has more than one dimension, it is called a multidimensional array. The number of dimensions is the number of indexes you need to identify an individual element. Lists of things are usually one-dimensional arrays. Tables are two dimensional arrays, and each element can be identified by giving the row and column index. Arrays with more than three dimensions are possible, but rarely used.
Sometimes the data structure in an application is two-dimensional but not rectangular. For example a calendar could be created as an array of months, with each month containing an array of days. Since different months have different numbers of days, the elements do not form a rectangular two-dimensional array.
Of course you could still use a two-dimensional array and just ignore the elements that represent invalid days (like 31st February). But you could also use a so called jagged array, or an array of arrays.
This is a one-dimensional array, of which each element contains an array again. These arrays don’t have to be of the same size, so it fits the non-rectangular data structure much better.
In VBA, you can’t declare a jagged array using the Dim
statement. Instead, you’ll declare a one-dimensional main array of type Variant
(both static or dynamic are possible). Since variables of data type Variant
can hold arrays, you can then assign the (sub)arrays to each element of this main array at run time. These (sub)arrays don’t need to be of type Variant
, the data type should correspond to the type of data that you want to store in them. But it’s also possible to make them Variant
again and put (sub)(sub)arrays in there.
While you’ll access a single element of a two dimensional array this way:
you’ll address a single element of a jagged array like this:
The following example shows how to create and work with both types of arrays using our calendar example:
'Work with a two-dimensional array Sub TestMulti() Dim i As Integer Dim myDays As Integer Dim myYear(1 To 12, 1 To 31) As String 'enter vacation days myYear(3, 15) = "Vacation" myYear(3, 16) = "Vacation" 'count vacation days For i = 1 To 31 If myYear(3, i) = "Vacation" Then myDays = myDays + 1 End If Next 'show result MsgBox "There are " & myDays & " vacation days in March." End Sub 'Work with an array of arrays Sub TestJagged() Dim i As Integer Dim myDays As Integer Dim myYear(1 To 12) As Variant Dim myMonth() As Variant 'create array of arrays For i = 1 To 12 'get correct number of days for a month myDays = Day(DateSerial(Year(Date), i + 1, 1) - 1) 'create array for month ReDim myMonth(1 To myDays) 'assign array to year myYear(i) = myMonth Next 'enter vacation days myYear(3)(15) = "Vacation" myYear(3)(16) = "Vacation" 'count vacation days myDays = UBound(Filter(myYear(3), "Vacation")) + 1 'show result MsgBox "There are " & myDays & " vacation days in March." End Sub
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:
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)
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:
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:
- Static – an array of fixed length.
- 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
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
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)
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, ",")
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”.
Before ReDim 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.
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:
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
Sample Student data
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
- Arrays are an efficient way of storing a list of items of the same type.
- You can access an array item directly using the number of the location which is known as the subscript or index.
- The common error “Subscript out of Range” is caused by accessing a location that does not exist.
- There are two types of arrays: Static and Dynamic.
- Static is used when the length of the array is always the same.
- Dynamic arrays allow you to determine the length of an array at run time.
- LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
- The basic array is one dimensional. You can also have multidimensional arrays.
- You can only pass an array to a procedure using ByRef. You do this like this: ByRef arr() as long.
- You can return an array from a function but the array, it is assigned to, must not be currently allocated.
- A worksheet with its rows and columns is essentially a two-dimensional array.
- You can read directly from a worksheet range into a two-dimensional array in just one line of code.
- 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.)
Option Explicit Public Sub ВызовЭлементаМногомерногоДинамическогоМассиваМассива() Dim myArr() As Long ReDim myArr(1 To 2, 0 To 1, 5 To 7) myArr(1, 0, 5) = Array(1, 2, 3, 4, 5) myArr(1, 0, 6) = Array(1, 2, 3, 4, 5, 6) myArr(1, 0, 7) = Array(1, 2, 3, 4, 5, 6, 7) myArr(1, 1, 5) = Array(1, 2, 3, 4) myArr(1, 1, 6) = Array(1, 2, 3, 4, 5) myArr(1, 1, 7) = Array(1, 2, 3, 4, 5, 6) myArr(2, 0, 5) = Array(1) myArr(2, 0, 6) = Array(1, 2) myArr(2, 0, 7) = Array(1, 2, 3) myArr(2, 1, 5) = Array(11, 12, 13, 14) myArr(2, 1, 6) = Array(11, 12, 13, 14, 15) myArr(2, 1, 7) = Array(11, 12, 13, 14, 15, 16) Debug.Print myArr(2, 1, 7) ' вызовем "вложенный" массив, например, для суммирования, думаю, должно возвратить 11, 12, 13, 14, 15, 16 Debug.Print myArr(2, 1, 7)(1) ' вызовем только один элемент "вложенного" массива,думаю, должно возвратить 11 Debug.Print myArr(2, 1, 7)(3) ' вызовем только один элемент "вложенного" массива, думаю, должно возвратить 13 End Sub
What is VBA Arrays in Excel?
A VBA array in excel is a storage unit or a variable which can store multiple data values. These values must necessarily be of the same data type. This implies that the related values are grouped together to be stored in an array variable.
For example, a large organization which operates in several countries employs 10,000 people. To store the details of all employees, a database containing hundreds of rows and columns is created. So, either of the following actions can be performed:
- Create multiple variables to fetch the cell values and give them to the program.
- Create an array consisting of multiple related values.
The action “a” is far more complicated and time-consuming than action “b.” For this reason, we use VBA arrays.
To use an array variable, it needs to be declared or defined first. While declaring, the length of the array may or may not be included.
The purpose of using an array is to hold an entire list of items in its memory. In addition, with an array, it is not required to declare each variable to be fetched from the dataset.
The difference between an array and a regular variable of VBAIn VBA, «public variables» are variables that are declared to be used publicly for all macros written in the same module as well as macros written in different modules. As a result, variables declared at the start of any macro are referred to as «Public Variables» or «Global Variables.»read more is that the latter can hold a single value at a given time. Moreover, while using multiple regular variables, every variable needs to be defined prior to its usage.
Table of contents
- What is VBA Arrays in Excel?
- The Properties of VBA Arrays
- The Working of a VBA Array
- Types of VBA Arrays
- #1 – Static Array
- #2 – Dynamic Array
- #3 – One-dimensional Array
- #4 – Two-dimensional Array
- #5 – Multi-dimensional Array
- How to use Arrays in VBA?
- The Procedure of Using an Array
- The Cautions Governing the use of VBA Arrays
- Frequently Asked Questions
- Recommended Articles
The Properties of VBA Arrays
The properties of VBA arrays are listed as follows:
- In an array, the data of the same type are grouped together. So, creating an array is similar to creating a separate memory unit which can hold data.
- The array to be used must correspond with the kind of dataset. For instance, if the dataset has a single row or a single column, a one-dimensional array is used. A two-dimensional array is used if the dataset has multiple rows and columnsA cell is the intersection of rows and columns. Rows and columns make the software that is called excel. The area of excel worksheet is divided into rows and columns and at any point in time, if we want to refer a particular location of this area, we need to refer a cell.read more.
- An array can function as static or dynamic. A dynamic array can include an infinite number of rows and columns. In contrast, a static array holds a limited number of rows and columns, which are defined at the time of creation.
Note: During run time, the size of a static array cannot be modified while a dynamic array can be resized.
The Working of a VBA Array
An array works similar to the mathematical rule of a matrix. This implies that an array identifies the data by its location.
For example, if the number 20 is required in cell B3, we write the location in the code as (3, 2). The number “3” represents the row number and “2” represents the column number.
In Excel, the code of locations is known as upper bound and lower bound. By default, the locations in Excel begin from 0 and not from 1. Hence, “A1” is considered as row number 0 and not as row number 1.
Likewise, columns also begin from 0 and not from 1.
Note: In the preceding example of cell B3, Excel counts the rows and columns from 1.
If we define this array as static, it cannot hold more than the defined variables. Hence, if the user is not sure about the number of values to be memorized by an array, it is advisable to use a dynamic array.
The data is entered in the array, as shown in the following image.
After storing data in an array, it is ready to be used as a variable in VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
Types of VBA Arrays
The VBA arrays can be categorized as follows:
- Static array
- Dynamic array
- One-dimensional array
- Two-dimensional array
- Multi-dimensional array
Let us consider every array one by one.
#1 – Static Array
A static array has a fixed, pre-defined count of the values that can be stored in it. The code of a static array is written as follows:
#2 – Dynamic Array
A dynamic array does not have a pre-defined count of values that can be stored in it. The code of a dynamic array is written as follows:
#3 – One-dimensional Array
A one-dimensional array can hold data either from a single row or a single column of Excel.
A table consists of the marks obtained by 5 students of a class. The Excel data and the code of a one-dimensional array are shown as follows:
#4 – Two-dimensional Array
A two-dimensional array can store values from multiple rows and columns of Excel.
A table consists of marks obtained by two students in Mathematics and Science. The Excel data and the code of a two-dimensional array are shown as follows:
#5 – Multi-dimensional Array
A multi-dimensional array can store data from multiple sheets which contain several rows and columns. An array can have a maximum of 60 dimensions.
A table consists of the marks obtained by two students in Mathematics, Science, and Accountancy. The Excel data and the code of a multi-dimensional array are shown as follows:
How to use Arrays in VBA?
You can download this Arrays in VBA Excel Template here – Arrays in VBA Excel Template
An array can be used in several situations. It is particularly used when there are a large number of variables to be declared and it is not feasible to define each and every variable.
The shortcut to open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more is “Alt+F11.”
Once the VBA editor opens, the code can be entered in “ThisWorkbook,” as shown in the following image.
The Procedure of Using an Array
The steps of using an array are listed as follows:
Step 1: Choose the type of array. It can be either dynamic or static.
For a dynamic array, the dimension is defined as “variant.”
For a static array, the dimension is defined as “static.”
Step 2: Define the rows and columns to be stored in the array.
Enter “1” within the brackets, as shown in the following image. This implies that the array can hold the values of two rows. This is because Excel begins counting from 0.
If rows and columns both are required, one needs to define them. So, enter “1 to 2” and “1 to 3” as arguments. The same is shown in the following image.
The argument “1 to 2” implies two rows and “1 to 3” implies three columns.
Note: In this case, Excel counts the rows and columns from 1 and not from 0.
Step 3: Enter the data as input in the array.
The data is entered in the form of (i,j), where “i” represents the row and “j” represents the column. Since the data is entered cell-wise, “a (1,1)” implies cell A1.
Hence, 30 will be entered in cell A1.
Step 4: Close the code.
Once the data for the array has been entered, the last step is to close the code. This is shown in the following image.
The Cautions Governing the use of VBA Arrays
The cautions to be observed while creating VBA arrays are listed as follows:
- Remember that by default, Excel counts the rows and columns beginning from zero. So, if “i” is 2, it implies three rows. The same applies to the column entries (j) as well.
- Ensure that the data entered in the array begins from (0,0), i.e., the first row and the first column.
- Use the “VBA REDIMThe VBA Redim statement increases or decreases the storage space available to a variable or an array. If Preserve is used with this statement, a new array with a different size is created; otherwise, the current variable’s array size is changed.read more” function to change the size of a dynamic array.
- Use “integer” as the dimension of a two-dimensional array that accepts integer values.
- Save the Excel file with the “.xlsm” extension otherwise, the VBA coding will not run the next time.
Frequently Asked Questions
1. Define VBA arrays.
A VBA array is capable of storing a series of data values. The condition is that all the values should be of the same data type. These values are known as the elements of an array.
For assigning values to an array, the location number of Excel is used. This number is known as the index or the subscript of an array. By default, the array index begins from zero unless an “Option Base 1” statement is entered at the beginning of the module.
With the “Option Base 1” statement, the array index begins from one.
Arrays are classified as follows:
• Static or dynamic based on whether the array size is fixed or changeable.
• One-dimensional, two-dimensional, or multi-dimensional based on the number of rows and columns of the source dataset from where values are assigned to an array.
2. Why are VBA arrays used?
An array is used for the following reasons:
• It helps avoid writing multiple lines of code. Since a regular variable can store a single value at a given time, each variable which is to be stored needs to be defined.
• It allows easy accessibility to the elements of the array. Every item of the array can be accessed with its row and column number which are specified while assigning values.
• It allows grouping the data of the same type. Since the related data is placed together, it simplifies working with large datasets.
• It adds the speed factor to working with Excel. Arrays make it easier to organize, retrieve, and alter data. This helps in improving productivity.
3. How to use the JOIN and SPLIT functions with respect to a VBA array?
The JOIN function combines several substrings of an array and returns a string. The JOIN function is the reverse of the SPLIT function.
The syntax of the JOIN function is stated as follows:
“Join(sourcearray,[delimiter])”
The arguments are explained as follows:
• Sourcearray: This is a one-dimensional array consisting of substrings to be joined.
• Delimiter: This is a character that separates the substrings of the output. If this is omitted, the delimiter space is used.
Only the argument “sourcearray” is required.
The SPLIT function divides the whole string into multiple substrings. It splits on the basis of the specified delimiter. It returns a one-dimensional and zero-based array.
The syntax of the SPLIT function is stated as follows:
“Split(expression,[delimiter,[limit,[compare]]])”
The arguments are explained as follows:
• Expression: This is the entire string which is to be split into substrings.
• Delimiter: This is a character like space, comma etc., that separates the substrings of the expression. If this is omitted, the space is considered as the delimiter.
• Limit: This is the number of substrings to be returned. It returns all the substrings if the limit is set at “-1.”
• Compare: This is the comparison method to be used. Either a binary (vbBinaryCompare) or textual comparison (vbTextCompare) can be performed.
Only the argument “expression” is required. The remaining arguments are optional.
Recommended Articles
This has been a guide to VBA Arrays. Here we discuss the different types of arrays, how to declare and use them. We also discussed the array in VBA examples. You can download the template from the website. You may also look at these useful Excel tools-
- Top 4 Error VLOOKUPThe top four VLOOKUP errors are — #N/A Error, #NAME? Error, #REF! Error, #VALUE! Error.read more
- VBA Books
- VBA Array Function in excelArrays are used in VBA to define groups of objects. There are nine different array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND.read more
Skip to content
The Variant data type, while inefficient, is necessary in many situations. You can create a Variant Array using the Array function like this
Dim vaTest As Variant
vaTest = Array(1, 2, 3)
You can also make the elements of your array arrays themselves, nested arrays if you will.
Dim vaTest As Variant
vaTest = Array(Array(1, 2, 3), Array(4, 5, 6))
Debug.Print vaTest(0)(1)
This bit of code will produce 2 in the Immediate Window. The syntax for accessing the nested array reads “Get the second element of the array that is the first element of vaTest. vaTest(0) accesses the first element of vaTest which is an array and (1) accesses the second element of that array.