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.)
Arrays are used to store data of similar data types. Suppose there are 300 students rather than declaring 300 variables for students, we can declare one array where we can store 300 elements. In this article, we will learn about excel VBA arrays.
Declaration of Array
Declaring an array is similar to declaring a variable in VBA. If we just mention, the size of a variable in parenthesis, then the variable becomes an array. For example, An array is declared with the name of arr, of 50. Here, the size of the array is 51, and the data type is the currency.
Syntax: Dim arr(size_of_array) as data_type
Note: In other programming languages, like C, C++, javascript, python etc. If an array of size n is created, then the indexes, range from [0, n-1], where 0 and n-1 are included, but in VBA by default, if an array of size n is created, then the indexes, range from [0, n], where 0 and n are included. Hence, VBA array of declaration n, is ultimately an array of size n+1.
Assigning Values to the Array
Assigning values means that an element is set to the value. For example, an array name arr of 50 is declared. Then a loop is passed on the array, and each element of the array is assigned the value 30.
Syntax: arr(index) = value
Changing Lower and Upper Bound
As, we discussed, above in a Note. That, arr(50), has an array size 51. So, what if we want to create an array of size 50, with 0-based or 1-based indexing? For example, if we want to change the lower bound from 0 to 1 then we can do it two ways:
Note: By default, the lower bound of an array is 0, and the upper bound of an array is n.
where,
lower bound is the lowest index of the array,
upper bound is the highest index of the array.
Using “Option Base”
Option Base statement is written at the top of the module to change the default index from 0 to 1.
Using the “To” clause
We can, Explicitly, can set the lower bound using the To clause. For example, arr(1 To 51), this array has a size of 50, with 1-based indexing.
Storing values of Variant data types in Arrays
Variant data types are those where any kind of data type can be stored like string, integer, date, etc. There are two methods, to store values in variant data types in arrays:
Method 1
The size of the array is predefined, i.e. 3. For example, an array of 2 is created. The value of arr[0] is a string, arr[1] is also a string, and arr[2] is a number.
Method 2
The size of the array is not predefined, and the values are assigned, directly to the array. Use, Array() function to achieve this. For example, arr = Array(“Ayush”, “123 Ayush”, 123).
Using Multidimensional Arrays
Declaration of a Multidimensional Array
We can declare a 2-dimensional array, by adding an additional size by comma separation. For example, if we want to create an array of 4 rows and 6 columns. Then the array declaration could be, Dim arr(1 To 4, 1 To 6) As Currency.
Syntax: Dim arr(Rows, Columns) As data_type
Assigning Values to a Multidimensional Array
We will use a nested For Next loop to assign the values in the multidimensional array. The below Picture illustrates the nested for loop, assigning of values in a multidimensional array.
Syntax: arr(i, j) = value
where,
i = index of the row,
j = index of the column,
value = the value which has to be assigned.
Functions in Arrays
There are ten-plus in-built functions in an array. These functions, help make our task more handy and easy. Here, we will discuss some of the most commonly used functions in arrays in VBA.
Erase
The Erase function clears all the elements in the array. For example, we have declared an array of size 3, and assigned values to them. Now, we want to erase all the elements in the array, i.e. Erase arr.
Syntax: Erase Array_name
where,
Array_name = It is the name of the array, whose elements are to be deleted.
ReDim
The ReDim() function is used to change the dimension of the array. For example, initially, we declared an array of size 3, now we want to reassign the value of dimension to 2 in the array. The ReDim arr(1 To 2) can be used to achieve this.
Syntax: ReDim Array_name(row, column)
where,
Array_name = It is the name of the array, for which the dimension has to be changed,
row = number of rows to be reassigned,
columns = number of columns to be reassigned
Join
The Join() function is used to join the elements of arrays into one variable. For example, an array of size 3, is created, and the values, assigned, to them are 10, 20, and 30. Now, if we want to concatenate, all the elements. Then, Join(arr) function can be used. The final output of the program will be 102030.
Syntax: Join(Array_name)
where,
Array_name: It is the name of the array. For example, arr in the below image.
Split
The Split() function, is used to split the string into an array, using a delimiter as a separator. For example, we have a string month_12 = “april,may,june”, now, we want to convert this string into an array, where each element is the name of the month. We can use Split(month_12, “,”), to achieve, this task. The final array will be (april, may, june).
Syntax: Split(string, delimiter)
where,
string = It is the string, from which the array has to be created,
delimiter = It is the separation parameter, on which basis the string will break into the array. For the below example, “,”(comma) is the delimiter.
Dim pos, arr, val
arr=Array(1,2,4,5)
val = 4
pos=Application.Match(val, arr, False)
if not iserror(pos) then
Msgbox val & " is at position " & pos
else
Msgbox val & " not found!"
end if
Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:
Dim arr(1 To 10, 1 To 2)
Dim x
For x = 1 To 10
arr(x, 1) = x
arr(x, 2) = 11 - x
Next x
Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)
EDIT: it’s worth illustrating here what @ARich pointed out in the comments — that using Index()
to slice an array has horrible performance if you’re doing it in a loop.
In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.
Sub PerfTest()
Const VAL_TO_FIND As String = "R1800:C8"
Dim a(1 To 2000, 1 To 10)
Dim r As Long, c As Long, t
For r = 1 To 2000
For c = 1 To 10
a(r, c) = "R" & r & ":C" & c
Next c
Next r
t = Timer
Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
' >> 0.00781 sec
t = Timer
Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
' >> 14.18 sec
End Sub
Function FindLoop(arr, val) As Boolean
Dim r As Long, c As Long
For r = 1 To UBound(arr, 1)
For c = 1 To UBound(arr, 2)
If arr(r, c) = val Then
FindLoop = True
Exit Function
End If
Next c
Next r
End Function
Function FindIndex(arr, val)
Dim r As Long
For r = 1 To UBound(arr, 1)
If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
FindIndex = True
Exit Function
End If
Next r
End Function
Объявление массива очень похоже на объявление переменной, за исключением того, что вам нужно объявить размер массива сразу после его имени:
Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings
По умолчанию массивы в VBA индексируются из ZERO , поэтому число внутри скобки не относится к размеру массива, а скорее к индексу последнего элемента
Доступ к элементам
Доступ к элементу массива осуществляется с использованием имени массива, за которым следует индекс элемента, внутри скобки:
myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"
Индексирование массива
Вы можете изменить индексирование массивов, разместив эту строку в верхней части модуля:
Option Base 1
С этой строкой все объявленные в модуле массивы будут проиндексированы с ONE .
Специфический указатель
Вы также можете объявить каждый массив своим собственным индексом, используя ключевое слово To
, а нижнюю и верхнюю границы (= индекс):
Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24
Динамическая декларация
Когда вы не знаете размер своего массива до его объявления, вы можете использовать динамическое объявление и ключевое слово ReDim
:
Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements
Обратите внимание, что использование ключевого слова ReDim
уничтожит любое предыдущее содержимое вашего массива. Чтобы предотвратить это, вы можете использовать ключевое слово Preserve
после ReDim
:
Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"
ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element
Использование Split для создания массива из строки
Функция разделения
возвращает одномерный массив на основе нуля, содержащий указанное количество подстрок.
Синтаксис
Split (выражение [, разделитель [, limit [, compare ]]] )
Часть | Описание |
---|---|
выражение | Необходимые. Строковое выражение, содержащее подстроки и разделители. Если выражение представляет собой строку нулевой длины («» или vbNullString), Split возвращает пустой массив, не содержащий элементов и данных. В этом случае возвращаемый массив будет иметь LBound 0 и UBound -1. |
ограничитель | Необязательный. Строковый символ, используемый для определения пределов подстроки. Если опустить, символ пробела («») считается разделителем. Если разделителем является строка с нулевой длиной, возвращается одноэлементный массив, содержащий всю строку выражения . |
предел | Необязательный. Количество подстрок, подлежащих возврату; -1 указывает, что все подстроки возвращаются. |
сравнить | Необязательный. Числовое значение, указывающее, какое сравнение следует использовать при оценке подстрок. См. Раздел «Настройки» для значений. |
настройки
Аргумент сравнения может иметь следующие значения:
постоянная | Значение | Описание |
---|---|---|
Описание | -1 | Выполняет сравнение, используя настройку оператора сравнения параметров . |
vbBinaryCompare | 0 | Выполняет двоичное сравнение. |
vbTextCompare | 1 | Выполняет текстовое сравнение. |
vbDatabaseCompare | 2 | Только Microsoft Access. Выполняет сравнение, основанное на информации в вашей базе данных. |
пример
В этом примере показано, как Split работает, показывая несколько стилей. В комментариях будет отображаться результирующий набор для каждого из разных вариантов Split. Наконец, показано, как перебирать возвращаемый массив строк.
Sub Test
Dim textArray() as String
textArray = Split("Tech on the Net")
'Result: {"Tech", "on", "the", "Net"}
textArray = Split("172.23.56.4", ".")
'Result: {"172", "23", "56", "4"}
textArray = Split("A;B;C;D", ";")
'Result: {"A", "B", "C", "D"}
textArray = Split("A;B;C;D", ";", 1)
'Result: {"A;B;C;D"}
textArray = Split("A;B;C;D", ";", 2)
'Result: {"A", "B;C;D"}
textArray = Split("A;B;C;D", ";", 3)
'Result: {"A", "B", "C;D"}
textArray = Split("A;B;C;D", ";", 4)
'Result: {"A", "B", "C", "D"}
'You can iterate over the created array
Dim counter As Long
For counter = LBound(textArray) To UBound(textArray)
Debug.Print textArray(counter)
Next
End Sub
Итерирующие элементы массива
Для … Далее
Использование переменной итератора в качестве номера индекса является самым быстрым способом для итерации элементов массива:
Dim items As Variant
items = Array(0, 1, 2, 3)
Dim index As Integer
For index = LBound(items) To UBound(items)
'assumes value can be implicitly converted to a String:
Debug.Print items(index)
Next
Вложенные циклы могут использоваться для итерации многомерных массивов:
Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3
Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
For inner = LBound(items, 2) To UBound(items, 2)
'assumes value can be implicitly converted to a String:
Debug.Print items(outer, inner)
Next
Next
Для каждого … Далее
A For Each...Next
цикл также может использоваться для повторения массивов, если производительность не имеет значения:
Dim items As Variant
items = Array(0, 1, 2, 3)
Dim item As Variant 'must be variant
For Each item In items
'assumes value can be implicitly converted to a String:
Debug.Print item
Next
A For Each
цикла будут выполняться итерация всех измерений от внешнего к внутреннему (в том же порядке, что и элементы, выделенные в памяти), поэтому нет необходимости в вложенных циклах:
Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3
Dim item As Variant 'must be Variant
For Each item In items
'assumes value can be implicitly converted to a String:
Debug.Print item
Next
Обратите внимание, что For Each
петли лучше всего использовать для итерации объектов Collection
, если имеет значение производительность.
Все 4 фрагмента выше дают одинаковый результат:
0
1
2
3
Динамические массивы (изменение размера массива и динамическая обработка)
Динамические массивы
Добавление и уменьшение переменных в массиве динамически является огромным преимуществом, когда информация, которую вы обрабатываете, не имеет определенного количества переменных.
Добавление значений динамически
Вы можете просто изменить размер массива с помощью ReDim
, это изменит размер массива, но если вы сохраните информацию, уже сохраненную в массиве, вам понадобится часть Preserve
.
В приведенном ниже примере мы создаем массив и увеличиваем его на еще одну переменную в каждой итерации, сохраняя значения уже в массиве.
Dim Dynamic_array As Variant
' first we set Dynamic_array as variant
For n = 1 To 100
If IsEmpty(Dynamic_array) Then
'isempty() will check if we need to add the first value to the array or subsequent ones
ReDim Dynamic_array(0)
'ReDim Dynamic_array(0) will resize the array to one variable only
Dynamic_array(0) = n
Else
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
Dynamic_array(UBound(Dynamic_array)) = n
'attribute a value to the last variable of Dynamic_array
End If
Next
Удаление значений динамически
Мы можем использовать ту же логику для уменьшения массива. В этом примере значение «последний» будет удалено из массива.
Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value
Сброс массива и повторное использование динамически
Мы также можем повторно использовать массивы, которые мы создаем, чтобы не иметь много памяти, что замедлит работу. Это полезно для массивов разных размеров. Один фрагмент кода можно использовать повторно использовать массив в ReDim
массив обратно (0)
, приписывать одной переменной в массив и снова свободно увеличивать массив.
В нижеприведенном фрагменте я создаю массив со значениями от 1 до 40, пуст массив и пополняем массив значениями от 40 до 100, все это выполняется динамически.
Dim Dynamic_array As Variant
For n = 1 To 100
If IsEmpty(Dynamic_array) Then
ReDim Dynamic_array(0)
Dynamic_array(0) = n
ElseIf Dynamic_array(0) = "" Then
'if first variant is empty ( = "") then give it the value of n
Dynamic_array(0) = n
Else
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
Dynamic_array(UBound(Dynamic_array)) = n
End If
If n = 40 Then
ReDim Dynamic_array(0)
'Resizing the array back to one variable without Preserving,
'leaving the first value of the array empty
End If
Next
Жесткие массивы (массивы массивов)
Ядра массивов НЕ многомерные массивы
Массивы массивов (Jagged Arrays) не совпадают с многомерными массивами, если вы думаете о них визуально. Многомерные массивы будут выглядеть как Matrices (Rectangular) с определенным количеством элементов по их размерам (внутри массивов), в то время как массив Jagged будет похож на ежегодный календарь с внутренними массивами, имеющими различное количество элементов, например, дни в разные месяцы.
Хотя Jagged Arrays довольно беспорядочны и сложны в использовании из-за их вложенных уровней и не имеют большой безопасности типов, но они очень гибкие, позволяют вам легко манипулировать различными типами данных и не нужно содержать неиспользуемые или пустые элементы.
Создание поврежденного массива
В приведенном ниже примере мы инициализируем зубчатый массив, содержащий два массива один для имен, а другой для чисел, а затем доступ к одному элементу каждого из них
Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements
Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")
OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside
Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element
Динамическое создание и чтение массивов с зубцами
Мы также можем быть более динамичными в нашем приближении, чтобы построить массивы, представьте, что у нас есть личный лист данных клиентов в excel, и мы хотим построить массив для вывода информации о клиенте.
Name - Phone - Email - Customer Number
Person1 - 153486231 - [email protected] - 001
Person2 - 153486242 - [email protected] - 002
Person3 - 153486253 - [email protected] - 003
Person4 - 153486264 - [email protected] - 004
Person5 - 153486275 - [email protected] - 005
Мы будем динамически строить массив заголовков и массив Customers, заголовок будет содержать заголовки столбцов, а массив Customers будет содержать информацию каждого клиента / строки в виде массивов.
Dim Headers As Variant
' headers array with the top section of the customer data sheet
For c = 1 To 4
If IsEmpty(Headers) Then
ReDim Headers(0)
Headers(0) = Cells(1, c).Value
Else
ReDim Preserve Headers(0 To UBound(Headers) + 1)
Headers(UBound(Headers)) = Cells(1, c).Value
End If
Next
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
For r = 2 To 6
'iterate through the customers/rows
For c = 1 To 4
'iterate through the values/columns
'build array containing customer values
If IsEmpty(Customer_Values) Then
ReDim Customer_Values(0)
Customer_Values(0) = Cells(r, c).Value
ElseIf Customer_Values(0) = "" Then
Customer_Values(0) = Cells(r, c).Value
Else
ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
End If
Next
'add customer_values array to Customers Array
If IsEmpty(Customers) Then
ReDim Customers(0)
Customers(0) = Customer_Values
Else
ReDim Preserve Customers(0 To UBound(Customers) + 1)
Customers(UBound(Customers)) = Customer_Values
End If
'reset Custumer_Values to rebuild a new array if needed
ReDim Customer_Values(0)
Next
Dim Main_Array(0 To 1) As Variant
'main array will contain both the Headers and Customers
Main_Array(0) = Headers
Main_Array(1) = Customers
To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.
Результатом приведенного выше фрагмента является массив с чередованием с двумя массивами, один из тех массивов с 4 элементами, 2 уровня отступа, а другой сам по себе является другим массивом Jagged, содержащим 5 массивов из 4 элементов каждый и 3 уровня отступа, см. Ниже структуру:
Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
(1) - Customers(0) - Array("Person1",153486231,"[email protected]",001)
Customers(1) - Array("Person2",153486242,"[email protected]",002)
...
Customers(4) - Array("Person5",153486275,"[email protected]",005)
Чтобы получить доступ к информации, которую вы должны иметь в виду о структуре созданного массива Jagged Array, в приведенном выше примере вы можете видеть, что Main Array
содержит массив Headers
и массив массивов ( Customers
), следовательно, с различными способами доступ к элементам.
Теперь мы прочитаем информацию о Main Array
и распечатаем каждую из данных Клиентов в виде Info Type: Info
.
For n = 0 To UBound(Main_Array(1))
'n to iterate from fisrt to last array in Main_Array(1)
For j = 0 To UBound(Main_Array(1)(n))
'j will iterate from first to last element in each array of Main_Array(1)
Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
'we can call the header with j as the header array has the same structure as the customer array
Next
Next
ЗАПОМНИТЕ, чтобы отслеживать структуру вашего Jagged Array, в приведенном выше примере для доступа к имени клиента, Main_Array -> Customers -> CustomerNumber -> Name
к Main_Array -> Customers -> CustomerNumber -> Name
который состоит из трех уровней, для возврата "Person4"
вам понадобится расположение клиентов в Main_Array, затем местоположение клиента 4 в массиве Jagged Customers и, наконец, местоположение Main_Array(1)(3)(0)
элемента в этом случае Main_Array(1)(3)(0)
который является Main_Array(Customers)(CustomerNumber)(Name)
.
Многомерные массивы
Многомерные массивы
Как видно из названия, многомерные массивы представляют собой массивы, которые содержат более одного измерения, обычно два или три, но могут иметь до 32 измерений.
Массив массива работает как матрица с различными уровнями, например, сравнение между одним, двумя и тремя измерениями.
Одно измерение — ваш типичный массив, он выглядит как список элементов.
Dim 1D(3) as Variant
*1D - Visually*
(0)
(1)
(2)
Два измерения будут выглядеть как сетка Sudoku или лист Excel, при инициализации массива вы определяете, сколько строк и столбцов будет иметь массив.
Dim 2D(3,3) as Variant
'this would result in a 3x3 grid
*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)
Три измерения начнут выглядеть как кубик Рубика, при инициализации массива вы будете определять строки и столбцы, а также уровни / глубины, которые будет иметь массив.
Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid
*3D - Visually*
1st layer 2nd layer 3rd layer
front middle back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)
Дальнейшие измерения можно рассматривать как умножение 3D, поэтому 4D (1,3,3,3) будет представлять собой два боковых боковых 3D-массива.
Двухмерный массив
Создание
Пример ниже будет компиляцией списка сотрудников, каждый сотрудник будет иметь набор информации в списке (имя, фамилия, адрес, электронная почта, телефон …), пример, по существу, будет храниться в массиве ( сотрудник, информация), являющееся (0,0), является первым именем первого сотрудника.
Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want
Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements
Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements
For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
For information_e = 0 To UBound(Employees, 2)
'for each information element/column in the array
Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
'iterating the full array will allow for direct attribution of information into the element coordinates
Next
Next
Изменение размера
Изменение размера или ReDim Preserve
Multi-Array, как и норма для массива One-Dimension, приведет к ошибке, вместо этого информация должна быть перенесена в массив Temporary с тем же размером, что и оригинал, плюс число добавляемых строк / столбцов. В приведенном ниже примере мы увидим, как инициализировать Temp Array, передать информацию из исходного массива, заполнить оставшиеся пустые элементы и заменить массив temp на исходный массив.
Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array
'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
For info = LBound(Employees, 2) To UBound(Employees, 2)
'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
TempEmp(emp, info) = Employees(emp, info)
Next
Next
'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray
For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
TempEmp(emp, info) = InformationNeeded & "NewRow"
Next
Next
'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp
Изменение значений элементов
Изменение / изменение значений в определенном элементе может быть выполнено путем простого вызова координаты для изменения и предоставления ей нового значения: Employees(0, 0) = "NewValue"
В качестве альтернативы, итерация по координатам использует условия для соответствия значениям, соответствующим требуемым параметрам:
For emp = 0 To UBound(Employees)
If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
'if value found
Employees(emp, 1) = "Married, Last Name Change"
Exit For
'don't iterate through a full array unless necessary
End If
Next
Доступ к элементам в массиве может выполняться с помощью вложенного цикла (итерация каждого элемента), цикла и координат (итерации строк и доступа к столбцам напрямую) или прямого доступа к обеим координатам.
'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
For info = LBound(Employees, 2) To UBound(Employees, 2)
Debug.Print Employees(emp, info)
Next
Next
'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
Debug.Print Employees(emp, 0)
Debug.Print Employees(emp, 1)
Debug.Print Employees(emp, 2)
Debug.Print Employees(emp, 3)
Debug.Print Employees(emp, 4)
Debug.Print Employees(emp, 5)
Next
'directly accessing element with coordinates
Debug.Print Employees(5, 5)
Помните , всегда удобно хранить карту массива при использовании многомерных массивов, они могут легко стать путаницей.
Трехмерный массив
Для 3D-массива мы будем использовать ту же предпосылку, что и 2D-массив, с добавлением не только хранения Employee и Information, но и построения, в котором они работают.
В трехмерном массиве будут присутствовать сотрудники (могут рассматриваться как строки), информация (столбцы) и здание, которые можно рассматривать как разные листы на документе excel, они имеют одинаковый размер между ними, но каждый лист имеет различный набор информации в своих ячейках / элементах. 3D-массив будет содержать n число 2D-массивов.
Создание
3D-массив нуждается в трех координатах для инициализации Dim 3Darray(2,5,5) As Variant
первой координатой массива будет количество строений / таблиц (разные наборы строк и столбцов), вторая координата будет определять строки и третью Столбцы. В результате Dim
выше будет создан трехмерный массив с 108 элементами ( 3*6*6
), эффективно имеющий 3 разных набора 2D-массивов.
Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements
For building = 0 To UBound(ThreeDArray, 1)
'for each building/set in the array
For employee = 0 To UBound(ThreeDArray, 2)
'for each employee/row in the array
For information_e = 0 To UBound(ThreeDArray, 3)
'for each information element/column in the array
ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
'iterating the full array will allow for direct attribution of information into the element coordinates
Next
Next
Next
Изменение размера 3D-массива аналогично изменению размера 2D, сначала создайте временный массив с тем же размером оригинала, добавляя его в координату параметра для увеличения, первая координата увеличит количество наборов в массиве, второе и третьи координаты увеличат количество строк или столбцов в каждом наборе.
Пример ниже увеличивает количество строк в каждом наборе на единицу и заполняет те недавно добавленные элементы новой информацией.
Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array
'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
Next
Next
Next
'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
TempEmp(building, emp, info) = InformationNeeded & "NewRow"
Next
Next
Next
'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp
Изменение значений элементов и чтение
Чтение и изменение элементов в 3D-массиве может быть выполнено аналогично тому, как мы делаем 2D-массив, просто отрегулируйте дополнительный уровень в петлях и координатах.
Do
' using Do ... While for early exit
For building = 0 To UBound(ThreeDArray, 1)
For emp = 0 To UBound(ThreeDArray, 2)
If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
'if value found
ThreeDArray(building, emp, 1) = "Married, Last Name Change"
Exit Do
'don't iterate through all the array unless necessary
End If
Next
Next
Loop While False
'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
Debug.Print ThreeDArray(building, emp, info)
Next
Next
Next
'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
Debug.Print ThreeDArray(building, emp, 0)
Debug.Print ThreeDArray(building, emp, 1)
Debug.Print ThreeDArray(building, emp, 2)
Debug.Print ThreeDArray(building, emp, 3)
Debug.Print ThreeDArray(building, emp, 4)
Debug.Print ThreeDArray(building, emp, 5)
Next
Next
'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)
Массивы в 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) |
If you’ve been working with (or learning) Visual Basic for Applications, you’re probably aware of the importance of having a solid knowledge of certain topics that influence data storage and manipulation. I’ve written detailed and comprehensive tutorials about several of these topics, including the following 2:
- Declare Variables In VBA For Excel: The How-To Guide.
- Excel VBA Data Types: The Complete Guide.
In this VBA tutorial, I focus on a topic that is closely related to the above:
Excel VBA arrays.
You’ll be glad to know that, if you already have a basic knowledge of variables and data types (I cover these topics in the blog posts I link to above), you already have a good base knowledge that will help you understand and master the topic of arrays.
After all, arrays are (in the end) variables. Therefore, working with VBA arrays is (to a certain extent) very similar to working with regular variables. Arrays have, however, certain special characteristics and features that differ from those regular variables.
You might be wondering why should you bother learning about Excel VBA arrays if you already have a good knowledge of regular variables.
To put it simply:
You should learn to work with Excel VBA arrays because, among other benefits (as listed in Excel 2016 VBA and Macros), they:
- Allow you to group related data and, more generally, make data manipulation easier.
- Help you ease the process of getting information from data.
- Can make your code more readable and easier to maintain.
- Allow you to increase the speed of your VBA applications.
An indication of the power of VBA arrays is provided by author Richard Mansfield. In Mastering VBA for Microsoft Office 2016, Mansfield describes arrays as “kind of super variable[s]” or “variable[s] on steroids”.
My purpose with this VBA tutorial is to provide you with a comprehensive and detailed introduction to the topic of Excel VBA arrays that allows you to start using arrays now. The following table of contents lists the main sections of this blog post. Please feel free to use it to easily navigate to the topic of your interest.
This Excel VBA Array Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Now:
Even though I’ve already provided a basic description of arrays in the introduction above, let’s start by diving deeper into the topic of…
What Is An Excel VBA Array
According to the Microsoft Dev Center, an array is:
A set of sequentially indexed elements having the same intrinsic data type. Each element of an array has a unique identifying index number. Changes made to one element of an array don’t affect the other elements.
In Excel VBA Programming For Dummies, Excel guru John Walkenbach provides a broader definition of array by stating that:
An array is a group of variables that share a name.
These 2 definitions provide a good idea of the basic characteristics of a VBA array that you need to understand for purposes of this tutorial. These main characteristics of a VBA array are:
- For purposes of Visual Basic for Applications an array is, basically, a group of variables.
- The group of variables that make up an array have (i) the same name, and (ii) the same data type.
- The variables that compose an array are sequentially indexed. Therefore, each array element has a unique identifying index number.
- You can make changes to a particular array element without changing the other elements.
At the same time, and as explained in Mastering VBA for Microsoft Office 2016, you can work with the whole array (all of its elements) at once
Let’s move on to one of the most important topics of this tutorial:
How To Declare An Excel VBA Array
As explained in Excel VBA Programming For Dummies, you must always declare an array before using it.
From a general perspective, you declare arrays the same way you declare other variables. This is because an array is itself a variable.
As I explain in my separate VBA tutorial about declaring variables, you can generally use 4 keywords to declare a variable explicitly:
- Dim.
- Static.
- Public.
- Private.
You can generally use those same 4 statements to declare an array. Therefore, if you understand how to declare variables in VBA, you already have the basic knowledge that is required to declare arrays.
Another important similarity is that when declaring arrays, you can specify their data type (just as you do with variables).
At a very basic level, there’s 1 main difference between declaring a regular (scalar) variable and an array:
When you declare an array, you usually have to specify the size of the array. When you declare a scalar variable (not an array), you don’t have to specify its size.
As a consequence of the above, the 4 elements you must consider when building a statement to declare an array are the following:
- Element #1: The keyword you’re using to declare the array.
As I mention above, you can use 4 different keywords for these purposes: (i) Dim, (ii) Static, (iii) Public and (iv) Private.
- Element #2: The name of the array.
- Element #3: The size of the array.
The following sections explain how this item differs depending on whether you’re declaring a fixed or a dynamic Array.
- Element #4: The data type for the array.
Therefore, a statement that declares an array using the items above has (roughly) the following structure:
Declaring_Keyword Array_Name([Array_Size]) [As Data_Type]
Items within square brackets ([ ]) are optional. Within this statement:
- Item #1 (Declaring_Keyword) is 1 of the 4 keywords that you can use to declare an array (Dim, Static, Public or Private).
- Item #2 (Array_Name) is the name of the array.
- Item #3 (Array_Size) is the size of the array. This item is usually referred to as the array or dimension subscripts.
The following sections focus on how you work with this particular item depending on whether you’re declaring a fixed or a dynamic Array. Whether the array is fixed or dynamic determines whether the Array_Size is optional or mandatory.
- Item #4 (Data_Type): is the data type for the array.
This item is optional.
Items #1 (Declaring_Keyword), #2 (Array_Name) and #4 (Data_Type) are substantially the same as those that you use when declaring variables in VBA.
Item #3 (Array_Size), as anticipated above, is the basic difference between declaring a scalar variable and an array. As a result of this root difference between variable and array declaration, there are 4 additional topics that you must consider when declaring an array (vs. when declaring a scalar variable):
- Topic #1: Array size and memory requirements.
- Topic #2: One-dimensional vs. multidimensional arrays.
- Topic #3: Fixed vs. dynamic arrays.
- Topic #4: Lower array bounds.
The following sections explain each of these topics. Let’s start by taking a look at:
Array Size, Data Types And Memory Requirements
As I explain above, you can specify the data type of an array when you declare it. For general purposes, the explanations and comments about the topic that I provide in this tutorial are applicable.
As a consequence of this, whenever you don’t declare the data type for an array, Visual Basic for Applications uses the default data type. This default data type is Variant. However, you may want to declare arrays using a different data type (other than Variant).
The main reason for this is that there’s an inverse relationship between execution speed and the amount of bytes used by the relevant data. The more bytes your data uses, the slower the execution of your VBA application. In practice, this may not be a big issue, assuming that you’re working on a computer with enough available memory. However, if you work with very large (particularly multidimensional) arrays, you may notice a difference in performance.
An exception to this rule is if you want the array to hold different data types. In such a case, the array data type must be Variant. This is because, as explained by Richard Mansfield in Mastering VBA for Microsoft Office 2016:
An array with the Variant data type can store multiple subtypes of data.
When deciding how to proceed, remember that different data types have different nominal allocation requirements. The following table provides a basic idea of how many bytes of memory are usually required by several of the main VBA data types:
Data Type of Element | Bytes |
---|---|
Variant (numeric) | 16 |
Variant (string) | 22 + string requirement |
Byte | 1 |
Boolean | 2 |
Currency | 8 |
Date | 8 |
Double | 8 |
Integer | 2 |
Long | 4 |
Object | 4 |
Single | 4 |
String (variable-length) | 10 + string requirement |
String (fixed-length) | String requirement |
The above values however, don’t provide all the information you need to understand how much memory a particular array needs. More precisely:
When calculating how many bytes an array uses, you must generally consider the following 2 factors:
- Factor #1: The data type of the array.
- Factor #2: The number of elements in the array.
You can get an idea of the array size is determined by multiplying (i) the amount of bytes required by the relevant data type and (ii) the number of array elements. In mathematical terms:
Bytes used by array = (# of elements in array) x (bytes required by each element of array data type)
According to the Microsoft Dev Center (in the webpage I link to above), the maximum size of a VBA array depends on 2 main factors:
- Your operating system.
- Available memory.
As a general rule, execution is slower whenever you use an array whose size exceeds the RAM memory that’s available in the system you’re working with. This is because, as explained by Microsoft, “the data must be read from and written to disk”.
Now that you have a basic understanding of the relationship between array size, data types and memory requirements, let’s move on to the topic of…
One-Dimensional And Multidimensional VBA Arrays
The Dim keyword is short for “Dimension”. As I quote in the post about declaring VBA variables, the only use of Dim in older BASIC versions was to declare the dimensions of an array.
VBA arrays can have up to 60 dimensions. However, in practice you’ll usually work with (maximum) 2 or 3 dimensional arrays.
In order to understand what a dimension is, let’s take a look at the simplest case: a one-dimensional array. One-dimensional arrays can be visualized as a single line of items. The following image shows an illustration of an 8-element one-dimensional array.
If you add an additional dimension, you have a two-dimensional array. You can think of such an array as a grid where the elements are arranged in rows and columns. The following image illustrates a two-dimensional array with 16 elements organized in 4 rows and 4 columns.
Notice how, in this particular case, I refer to each array element by using 2 numbers. The first number makes reference to the location within the first dimension (in this image the row) row where the element is located. The second number refers to the location in the second dimension (in this case, the column). I explain the topic of how to refer to array elements below.
If, once more, you add an additional dimension, you get a three-dimensional array. You can picture this array as a cube.
I can’t provide an image to illustrate arrays of 4 or more dimensions. In any case, the purpose of the previous image is just to provide you a visual idea of what an array is.
Within the Visual Basic Editor, an array looks different. In the following sections, I provide several examples of statements that declare both one-dimensional and multidimensional arrays.
Fixed And Dynamic VBA Arrays
As I mention above, the basic difference you must be aware of when declaring an array (vs. a scalar variable) is that you usually specify the size of the array.
There are, however, 2 ways in which you can go about determining an array size:
- Option #1: You can specify the size of the array. This results in a fixed-size array (fixed array).
- Option #2: You can allow the size of the array to change as the relevant application runs. The result of this option is a dynamic array.
The usage of dynamic arrays is substantially the same as that of fixed arrays. The main difference between them is that fixed arrays are “un-resizable”.
As I explain above, the basic structure of the statement you can use to declare an array is as follows:
Declaring_Keyword Array_Name([Array_Size]) As [Data_Type]
I explain items #1 (Declaring_Keyword), #2 (Array_Name) and #4 (Data_Type) above.
I cover item #3 (Array_Size) in the following sections. Let’s start by taking a look at…
How To Declare A Fixed One-Dimensional Excel VBA Array
As a general rule, you set the size of an array dimension (Array_Size in the array declaration statement above) through the following 3 items:
- Item #1: The first index number.
- Item #2: The keyword “To”.
- Item #3: The last index number.
In other words, the structure of the statement you use to declare an array can be rewritten as:
Declaring_Keyword Array_Name(First_Index_# To Last_Index_#) [As Data_Type]
This is perhaps the most basic array declaration you can make.
All the array declaration statements that I include as examples in this VBA tutorial use the Dim statement. Remember that, as I explain above, you can (theoretically) also use Private, Public or Static. The comments I make throughout this blog post generally apply to the cases where you’re working with those other statements as well.
Let’s take a look at 2 examples:
- Example #1: The following statement declares an array of 10 integers (elements 0 to 9):
Dim myArray(0 To 9) As Integer
- Example #2: This statement declares an array of 20 strings (elements 0 to 19):
Dim myArray(0 To 19) As String
Strictly speaking, you can set the size of an array by only specifying the upper index number. In other words, you can declare an array by omitting:
- Item #1: The first index number.
- Item #2: The keyword “To”.
Let’s take a look at how the 2 statement examples above look like if I declare them without a lower index:
- Example #1: 10-integer array.
Dim myArray(9) As Integer
- Example #2: Array composed of 20 strings.
Dim myArray(19) As String
In such cases, Visual Basic for Applications assumes that the lower index number is 0 (by default) or 1 (if you use the Option Base 1 statement). I explain this topic below. For the moment, note the following 2 points:
- #1: The arrays declared by the statement samples above have 0 as lower index.
- #2: This way of declaring an array doesn’t specify the number of array elements. It rather specifies the upper array bound.
As you start working with arrays, in any case, you may start realizing that including both an upper and a lower bound when declaring an array provides more flexibility than relying on the Option Base statement. Additionally, in certain cases, omitting the lower array bound may lead to bugs.
Due to, among others, these reasons, I personally prefer specifying both the upper and lower bound of an array over allowing the Option Base statement to determine the lower array boundary. VBA experts such as Chip Pearson (who I quote above) probably agree with this opinion. Chip’s opinion, which you can find by following the link above, is that it’s a…
Very poor programming practice to omit the lower bound and declare only the upper bound.
How To Declare A Fixed Multidimensional Excel VBA Array
The statement for declaring a fixed multidimensional array is very same to the statements that we’ve seen above to declare a one-dimensional array.
In practice, the main difference between declaring a one-dimensional and a multidimensional array is that, when declaring a multidimensional array, you separate the size of the dimensions with commas (,).
Therefore, the structure of the statement you use to declare an array with ## dimensions can be rewritten as:
Declaring_Keyword Array_Name(Dimension1_First_Index_# To Dimension1_Last_Index_#, Dimension2_First_Index_# To Dimension2_Last_Index_#, … , Dimension##_First_Index_# To Dimension##_Last_Index_#) [As Data_Type]
Let’s take a look at some examples of fixed multidimensional array declarations:
- Example #1: The following statement declares a two-dimensional array with 25 integers. As I explain above, you can think of this array as a 5 x 5 grid.
Dim myArray(1 To 5, 1 To 5) As Integer
- Example #2: This statement declares a three-dimensional array with 1,000 integers. Following the logic behind the illustrations above, you can picture this as a 10 x 10 x 10 cube.
Dim myArray(1 To 10, 1 To 10, 1 To 10) As Integer
- Example #3: The following statement declares a four-dimensional array with 10,000 integers:
Dim myArray(1 To 10, 1 To 10, 1 To 10, 1 To 10) As Integer
How To Declare And ReDim A Dynamic Excel VBA Array
As I explain above, the size of dynamic arrays changes as the relevant application runs. In other words (as explained in Excel VBA Programming for Dummies):
A dynamic array doesn’t have a preset number of elements.
The following are 2 of the main reasons to use dynamic arrays are:
- Reason #1: You don’t know what is the required array size prior to execution.
- Reason #2: You want to optimize memory usage by, for example, allocating very large arrays for only short periods of time.
When declaring a dynamic array, you don’t include a number of elements (Array_Size within the basic syntax above) in the declaration statement. This means that you leave the relevant set of parentheses empty.
The basic syntax of a statement declaring a dynamic array is, therefore, as follows:
Declaring_Keyword Array_Name() [As Data_Type]
The following sample statements declare dynamic arrays:
Dim myArray() As Integer
Dim myArray() As String
You can’t, however, use a dynamic array until you have specified how many elements the dynamic array has. To do this, you use the ReDim statement.
Let’s take a closer look at this topic:
ReDim Dynamic Array
The main purpose of the ReDim statement is to allow you to “reallocate storage space” for dynamic arrays. As I mention above, you use the ReDim statement to specify the number of elements that a dynamic array has.
You can’t use the ReDim statement to resize a fixed array. As explained at the Microsoft Dev Center, whenever…
You try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
The basic syntax of the ReDim statement is, to a certain extent, similar to that you use when declaring an array (which I explain above). More precisely, the basic structure is as follows:
ReDim [Preserve] Array_Name(Array_Size) [As Data_Type]
Items within square brackets ([ ]) are optional.
This statement contains the following 5 items:
- Item #1: ReDim keyword.
I explain the purpose of this keyword in the current section.
- Item #2: Preserve keyword.
This item is optional. I explain its purpose and characteristics further below.
- Item #3: Array_Name.
This is the name of the array you’re working with. I explain this element in the section above that covers the topic of declaring VBA arrays.
- Item #4: Array_Size.
This is the size of the array. This particular element is the one you’re usually specifying when working with the ReDim statement.
I explain how you deal with this item starting in this section.
- Item #5: As Data_Type.
I introduce this particular item when explaining how to declare an array in a previous section. The comments I provide there generally apply to the cases where you’re using the ReDim Statement.
Despite the above, there are a couple of particular rules that apply when you’re working with the ReDim statement. I explain these below.
As a general rule, you can use the ReDim statement as many times as you require in order to change the size of your dynamic arrays.
Despite the above, you can’t always redimension an array. More precisely, whenever you pass a VBA array to a procedure by reference, you can’t redimension that array within that procedure.
Let’s take a look at some particularities of the ReDim statement, before moving on to a code example:
The ReDim Statement And Data Types
As a general rule, you can’t use the ReDim statement to change an array data type that you’ve declared previously.
The basic exception to this rule are the cases where the array is contained in a Variant variable. In such cases, you can usually use item #5 above (As Data_Type] to change the data type.
Even in the cases where the array is contained in a Variant variable, you won’t be able change the array data type if your ReDim statement uses the Preserve keyword. This is because, when you’re using “Preserve”, data type changes are not allowed.
Independent of the above, note that in order to be able to resize an array contained in a Variant variable, you must declare the variable explicitly. The declaration statement must be before the statement that resized the array.
Now, let’s go back to…
The Preserve Keyword
As explained in Excel 2016 VBA and Macros, the ReDim statement “reinitializes” the array you’re working with. Therefore, as a general rule, ReDim erases any previously stored data within an array’s elements. In other words, that old data is destroyed.
You can, however, avoid destroying all of the previously existing data by using the optional Preserve keyword within the ReDim statement. As implied by its name, you can use the Preserve keyword to preserve data within an array.
Using the Preserve keyword comes with some conditions attached. The following are the most relevant conditions you should be aware about:
- Condition #1: As explained in the previous section, data type changes aren’t generally allowed.
- Condition #2: You can’t change the number of dimensions of the array.
- Condition #3: You can only resize the last dimension of the array.
- Condition #4: You can only change the upper array bound.
Seen from the opposite perspective, you can’t change the lower bound of the array. If you try to do this, an error is caused.
Further to the above (although not strictly a condition), you may want to consider the fact that (as explained in Excel 2016 VBA and Macros), the Preserve keyword can slow down your VBA applications. This is the case, for example, when you have a large amount of data within a loop.
I provide some examples of ReDim statements that use the Preserve keyword below.
Reducing The Size Of A Dynamic Array
As a general rule, you can use the ReDim statement to reduce the size of a dynamic array.
In such cases, the data stored within the deleted elements is wiped out. This is the case even if you’re using the Preserve keyword.
ReDim Statement To Declare Variables
From a theoretical point of view, the ReDim statement can be used to declare variables. This is the case if ReDim makes reference to a variable that doesn’t exist at the module or procedure level.
Further to the above, as explained by Microsoft:
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.
Due to the problems/conflicts that may arise as a consequence of the above, it’s advisable to avoid using the ReDim statement to declare variables. In other words, limit the use of the ReDim statement to the situations where you’re redimensioning an array.
ReDim Statement Code Example
As explained by Excel authority John Walkenbach in Excel VBA Programming for Dummies, whenever you’re working with a dynamic array, it’s usual that…
The number of elements in the array is determined while your code is running.
Therefore, for purposes of the example below, let’s assume the following 2 things:
- Assumption #1: You’re working in a particular procedure that includes a variable named “dimensionSize”.
- Assumption #2: The dimensionSize variable contains a certain value.
If that’s the case, the following sample statement uses the ReDim statement to change the size of the array:
ReDim myArray (1 to dimensionSize)
When working with a multidimensional array, you separate the size of the different dimensions with a comma (,). The logic is basically the same that I explain above for declaring a multidimensional array.
The following 3 statements are examples of how to use the ReDim statement when working with multidimensional arrays:
- Example #1: If you have 2 variables containing values (dimensionSize1 and dimensionSize 2):
ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2)
- Example #2: If you have 3 variables called “dimensionSize1” through “dimensionSize3”:
ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2, 1 to dimensionSize3)
- Example #3: If you have 4 variables (dimensionSize1 through dimensionSize4):
ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2, 1 to dimensionSize3, 1 to dimensionSize4)
Finally, the following statements are samples of how you can use the Preserve keyword within the ReDim statement to preserve data within the relevant array. I introduce the Preserve keyword above.
- Example #1: This example assumes that (i) the array (myArray) has 5 elements, and (ii) the dimensionSize variable has a value of 12. If that’s the case, the following statement preserves the data stored within the first 5 elements, and adds 7 new elements to the array (6 to 12):
ReDim Preserve myArray (1 to dimensionSize)
- Example #2: This example assumes that (i) myArray has 2 dimensions and 9 elements (3 x 3), and (ii) the dimensionSize variable has a value of 5. If this is the case, the following statement preserves the data stored within the array, and adds 6 new elements. The array size after this statement is 3 x 5.
ReDim Preserve myArray (1 to 3, 1 to dimensionSize)
- Example #3: This example assumes that (i) myArray has 3 dimensions and 8 elements (2 x 2 x 2), and (ii) dimensionSize’s value is equal to 5. In such a case, the following statements preserves the data stored in myArray and adds 12 elements. The resulting array size is 2 x 2 x 5.
ReDim Preserve myArray (1 to 2, 1 to 2, 1 to dimensionSize)
When looking at these last 3 examples, remember that (as I mention above) you can only resize the last dimension of an array when using the Preserve keyword.
In example #1, you only have 1 dimension. That dimension is also the last dimension. In examples #2 and #3 you have more than 1 dimension. Therefore, in those 2 cases, I only change the size of the last dimension.
Lower Array Bounds And The Option Base Statement
As I explain above, it’s not mandatory to express the lower bound of an array.
Doing so doesn’t mean that there’s no lower bound. As explained by Excel authorities Bill Jelen (Mr. Excel) and Tracy Syrstad in Excel 2016 VBA and Macros, when you do this you’re actually “allowing” the Option Base statement to determine the lower bound.
When you do this, there are 2 options for array indexing:
- Option #1: The array is indexed from 0.
- Option #2: The array is indexed from 1.
You can determine which of the above 2 options applies to a particular array by using the Option Base statement.
The default indexing option is Option Base 0. Therefore, if you don’t specify the base when declaring an array, it begins at 0. This is the most common standard in programming.
In order to implement option #2 and have the array be indexed from 1, you use the Option Base statement. To do this, enter the following statement at the top of the module you’re working in and before any procedures:
Option Base 1
The following image shows the top of a particular module that includes both the Option Explicit statement and the Option Base 1 statement within the General Declarations section before the first procedure (One_Dimensional_Array_Declaration_1):
The Option Base statement:
- Can only appear once per module.
- Must “precede array declarations that include dimensions”.
- Only changes the lower bound of arrays within the particular module that contains the Option Base statement.
You can’t use the Option Base statement to change the lower bound of arrays created using the ParamArray keyword. You may work with the ParamArray keyword to, among others, create User-Defined Functions that take an unlimited (up to 255) number of arguments.
Let’s go back to the examples of array declaration statements that I provide in the previous sections about fixed one-dimensional and fixed multidimensional arrays. The following examples assume that the relevant statement is within a module that contains the “Option Base 1” statement, as I explain above.
- Example #1: Both of the following statements declare an array of 10 integers (elements 1 to 10):
Dim myArray(1 To 10) As Integer
Dim myArray(10) As Integer
- Example #2: These statements declare an array with 20 strings (elements 1 to 20):
Dim myArray(1 To 20) As String
Dim myArray(20) As String
- Example #3: The following statements resize an array with a number of elements equal to the value held by the dimensionSize variable (elements 1 to dimensionSize):
ReDim myArray (1 to dimensionSize)
ReDim myArray (dimensionSize)
How To Refer To An Array Element
The previous sections of this Excel tutorial focus on what an array is and how you can declare different types of arrays. This section explains how you can refer to a particular element within an array.
As a general rule, in order to identify a particular element of an array, you use its index number(s) for each of the array dimensions. Therefore, the basic syntax of the statement you use varies depending on how many dimensions the relevant array has. The number of index number(s) you must include in the reference is equal to that number of dimensions.
The following sections start by explaining how you can refer to an element within a one-dimensional array (the most basic case). I later show how the syntax varies (slightly) when you’re referring to elements within multidimensional arrays.
How To Refer To An Element In A One-Dimensional Array
As explained in Excel 2016 Power Programming with VBA, you generally refer to an array element by using 2 items:
- Item #1: The name of the array.
- Item #2: A particular index or subscript number.
The basic structure of the statement you can use to refer to an element within a one-dimensional array is as follows:
Array_Name(Element_Index_Number)
Let’s take a look at some examples:
The sample macro displayed in the following image (One_Dimensional_Array_Declaration_1), does the following 3 things:
- Declares an array of 10 integers (1 to 10).
This statement follows the rules to declare a VBA array that I explain above.
- Initializes each array element and assigns the values 1 through 10 to each of these elements.
This particular VBA tutorial doesn’t focus on the topic of the different ways you can assign values to the elements of an array. Even though there are other ways to fill an array, the examples I use throughout this blog post individually assign a value to each array element.
I may dive deeper into the topic of array filling in a future blog post. If you want to receive an email whenever I publish new content in Power Spreadsheets, make sure to register for our Newsletter now by entering your email address below:
- Uses the MsgBox VBA function to display a dialog box with the value of the first element of the array (myArray(1)).
Notice how all of the element references within items #2 and #3 use the basic statement structure that I introduce above:
The effect of executing this sample macro is that Excel displays the following dialog box. Notice that the value within the message of the dialog is equal to that assigned to the first element of the array in the Sub procedure above.
The following section takes this a step further and shows you…
How To Refer To An Element In a Multidimensional Array
The logic to refer to an element within a multidimensional array, is similar. The main rules for making reference to such an element are the following:
- Rule #1: Include the relevant index number for each dimension of the array.
- Rule #2: Separate the different index numbers with commas (,).
As a consequence of these rules, the basic structure of a reference to an element within an array with ## dimensions is as follows:
Array_Name(Dimension1_Element_Index_Number, Dimension2_Element_Index_Number, …, Dimension##_Element_Index_Number)
The following sample macro (Two_Dimensional_Array_Declaration) does the same 3 things as the Sub procedure example in the previous section. More precisely, it:
- Declares an array of 9 integers (3 x 3).
I explain the syntax of this statement in a previous section of this tutorial.
- Initializes each array element and assigns values 1 through 9 to them.
- Displays a dialog box with the value of the first array element (1, 1).
The following image shows the dialog box that Excel displays when I execute this macro:
Notice how, as expected, the displayed value matches with that assigned to the first array element within the VBA code:
Let’s take a look at a final example macro (Three_Dimensional_Array_Declaration), where the macro works with a three-dimensional array. This sample macro does the following:
- Declares an array of 8 integers (2 x 2 x 2).
- Initializes each array element and assigns values 1 through 8 to each element.
- Displays a message box with the value assigned to the first array element (1, 1, 1).
The dialog box that Excel displays when I execute the macro is (as expected) substantially the same as that in the previous examples:
Notice how, once again, the value displayed by Excel matches that assigned to the first array element by the VBA code:
How To Erase The Data In An Array (Or The Array Itself)
As I explain above the ReDim statement generally wipes out the data within the array you’re working with.
You can, however, erase the data stored within an array with a different statement: Erase.
The main purpose of the Erase statement is to:
- Reinitialize the elements of a fixed array.
The Erase statement doesn’t recover memory when working with a fixed array. It generally sets the array elements to the default values of the relevant data type.
- Release “dynamic-array storage space”.
In the case of dynamic arrays, therefore, the Erase statement frees the memory that the array was using. This, basically, erases the dynamic array completely. Therefore, before you’re able to use the array in the future, you must specify how many elements it has by using the ReDim statement. I explain how to do this above.
The basic syntax of the Erase statement is quite straightforward:
Erase arraylist
For these purposes, arraylist is the list of array(s) to be erased. If you’re erasing more than 1 array, separate them with a comma (,).
The following sample statements show how you can use the Erase statement:
- Example #1: This statement erases the data stored within myArray (if it’s fixed) or myArray itself (if it’s dynamic):
Erase myArray
- Example #2: The following statement erases the data stored within both myArray1 and myArray2 (if they’re fixed) or the arrays themselves (if they’re dynamic):
Erase myArray1, myArray2
Conclusion
After reading this VBA tutorial, you probably have a very solid understanding of the topic of Excel VBA arrays. Among other things, you know:
- What are VBA arrays, and why they’re useful.
- What are one-dimensional and multidimensional VBA arrays. This includes their commonalities and differences.
- What are fixed and dynamic arrays, how they’re similar and how they differ.
- The relationship between array size, data types and memory requirements, and why this relationship is important.
- How can you declare an array depending on whether it’s fixed (one-dimensional or multidimensional) or dynamic.
- How are lower array bounds determined if you don’t explicitly specify them, and what is the Option Base statement.
- How to use the Erase statement when working with arrays.
This Excel VBA Array Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Books Referenced In This Excel Tutorial
- Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
- Jelen, Bill and Syrstad, Tracy (2015). Excel 2016 VBA and Macros. United States of America: Pearson Education, Inc.
- Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.
- Walkenbach, John (2015). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
Before I start, let me share a little secret with you… I really dislike VBA arrays. There just seem to be too many oddities in how they work. Compared with other programming languages, VBA seems to make arrays overly complicated. If you feel the same, then you’re in the right place. This post contains a lot of code examples, which will cover most of your use cases.
Thank you to Jon Peltier for suggesting how I can improve this post.
Download the example file
I recommend you download the example file for this post. Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.
Download the file: 0017 VBA Arrays.zip
What is an array & when to use it?
An array is a list of variables of the same type. For example, a list of supplier names would be an array.
Let’s assume we have a list of 5 suppliers that can change each month. Look at the screenshot below as an example:
To hold the supplier list, we could create 5 variables, then assign values from a worksheet to each variable. This is what the code might look like:
Sub ListSuppliers() 'Create the variables Dim Supplier1 As String Dim Supplier2 As String Dim Supplier3 As String Dim Supplier4 As String Dim Supplier5 As String 'Assign values to the suppliers Supplier1 = ActiveSheet.Range("A2").Offset(0, 0).Value2 Supplier2 = ActiveSheet.Range("A2").Offset(1, 0).Value2 Supplier3 = ActiveSheet.Range("A2").Offset(2, 0).Value2 Supplier4 = ActiveSheet.Range("A2").Offset(3, 0).Value2 Supplier5 = ActiveSheet.Range("A2").Offset(4, 0).Value2 End Sub
That doesn’t seem too bad, does it? Now imagine we have to list 1,000 suppliers, or 10,000 suppliers; that’s going to be a very dull day of coding. Unless, of course, we use an array.
Also, what if we have an unknown number of suppliers. What are we going to do then? We would need create more variables than we need just to ensure there is enough space. Again we can turn to a VBA array.
Look at the code below; it creates an array to hold 10,000 suppliers, populated from 10,000 cells in column A. You don’t need to understand it at this stage; instead, just be impressed with how neat and tidy it is. It’s difficult to believe that a VBA array containing a list of 10,000 items takes less code than a list of five variables.
Sub ListSuppliersArray() Dim Suppliers(1 To 10000) As String Dim i As Long For i = LBound(Suppliers) To UBound(Suppliers) Suppliers(i) = ActiveSheet.Range("A2").Offset(i - 1, 0).Value2 Next i End Sub
Using the VBA above, it doesn’t matter if there are 1, 20, 50, 1,000, or 10,000 items, the code will be the same length. This is the advantage of arrays; we don’t have to write the same code over and over. Instead we can write one piece of code which add all of the items into an array.
But, it doesn’t end there. If the values to assign are in a contiguous range, we can reduce the code to just a few lines. Look at the macro below; a range of 10,000 cells is assigned to a Variant variable type, which automatically creates an array of 10,000 items (no looping required). Amazing stuff, right?
Sub ListSuppliersArray() Dim Suppliers As Variant Suppliers = ActiveSheet.Range("A2:A10001").Value2 End Sub
OK, now we understand the benefits of VBA arrays, let’s learn how to use them.
Static vs. dynamic Arrays
Arrays come in two forms:
- Static – an array with a fixed number of elements
- Dynamic – an array where the number of elements is determined as the macro runs.
The difference between the two is how they are created. After that, accessing values, looping through elements and other actions are exactly the same.
Declaring an array as a variable
Arrays are declared in the same way as single value variables. The critical difference is that when declaring an array parentheses are often used after the variable name.
Declare a single variable
'Declare a string as a single variable Dim myVariable As String
Declare an array variable
'Declare a string as an array Dim myArray(1 to 5) As String
Arrays, like other variables can be any variable type. Integers, strings, objects and ranges, etc., can all be included in an array.
Using variant as an array
A variable declared as a Variant can hold any data type. Interestingly, a Variant type can also become an array if we assign an array to it.
Look at the code below. First, a standard variable with a Variant data type is created, then an array is assigned to the variable. As a result, the variable has become an array, and can be treated the same as other arrays.
Dim arrayAsVariant As Variant arrayAsVariant = Array("Alpha", "Bravo", "Charlie")
Create a static array
The following macro creates a static array with 5 elements (1, 2, 3, 4 & 5).
Sub CreateStaticArray() 'Create a static array with 5 elements (1, 2, 3, 4, 5) Dim arr(1 To 5) As Long End Sub
By default, arrays have base 0, which means they start counting at 0, rather than 1. The following macro creates a static array with 6 elements (0, 1, 2, 3, 4, 5). Notice that the array is created with 5 inside the parentheses, but because of base 0, there are actually 6 elements created.
Sub CreateStaticArrayStartingAtZero() 'Create a static array with 6 elements (0, 1, 2, 3, 4, 5) Dim arr(5) As Long End Sub
We can turn arrays into base 1 (i.e., counting starts at 1) by inserting the following code at the top of the code module.
Option Base 1
Create a static two-dimension array
Arrays can contain multiple dimensions (or sub-arrays). This is much like having data in rows and column. In the code below, we have created a static array of 3 elements, each of which is its own array containing another 3 elements.
Sub Create2DimensionStaticArray() Dim arr(1 To 3, 1 To 3) As String arr(1, 1) = "Alpha" arr(1, 2) = "Apple" arr(1, 3) = "Ant" arr(2, 1) = "Bravo" arr(2, 2) = "Ball" arr(2, 3) = "Bat" arr(1, 1) = "Charlie" arr(2, 2) = "Can" arr(3, 3) = "Cat" End Sub
We’re not limited to just two dimensions, VBA allows us up to 60! I don’t think I’ve very used more than 3, but it’s good to know that there are so many spare.
Create a dynamic array
The problem with static arrays is that we need to know how many elements are required when we create the array. But often we don’t know the number of elements, or maybe we want to add and remove elements from the array as we go. Instead, we can turn to dynamic arrays.
NOTE – The term “dynamic array” in Excel and VBA is not the same; they are entirely different methodologies.
The following macro initially creates a dynamic array with no size. Then, later in the macro, the array is resized, using ReDim, to create 5 elements, starting at 1.
Sub CreateDynamicArray() 'Create the array Dim arr() As Long 'Resize the array later in the macro ReDim arr(1 To 5) End Sub
A dynamic array can be resized many times during macro execution (we will see this later in this post).
Index locations
Each element of an array has an index number (i.e., the position in the array).
Index of the first element
The following macro displays the index number of the first element in an array.
Sub GetIndexOfFirstElement() 'Create the array Dim arr As Variant arr = Array("Alpha", "Bravo", "Charlie") 'Get the index number of the first element MsgBox LBound(arr) End Sub
LBound() is a function which returns the lowest item in the array.
Index of the last element
The following macro displays the index number of the last element in an array.
Sub GetIndexOfLastElement() 'Create the array Dim arr As Variant arr = Array("Alpha", "Bravo", "Charlie") 'Get the index number of the last item element MsgBox UBound(arr) End Sub
UBound() is a function which returns the highest item in the array.
Assigning values to an array
After creating an array, whether dynamic or static, we need a way to assign values to the individual elements.
Assign values to elements individually
The following macro creates a static array, then assigns values to each element individually.
Sub AssignFixedValuesToArray() Dim arr(1 To 5) As String arr(1) = "Alpha" arr(2) = "Bravo" arr(3) = "Charlie" arr(4) = "Delta" arr(5) = "Echo" End Sub
Assign values to elements with an array list
The following macro demonstrates how to assign values to a dynamic array based on a list of values.
Sub AssignValuesFromListToArray() 'Type must be Variant for method to work Dim arr As Variant arr = Array("Alpha", "Bravo", "Charlie") End Sub
The Array() command is a short way to add values to an array.
Assign values to elements with a string
The following macro splits a string into an array.
Sub SplitStringIntoArray() Dim arr As Variant Dim myString As String 'Create list with a by common seperator between each element myString = "Alpha, Bravo, Charlie, Delta, Echo" 'Turn the list into an array arr = Split(myString, ", ") End Sub
Assign values to elements from a range
The following macro creates a 2-dimensional array directly from a range.
Sub ReadRangeToArray() Dim arr As Variant arr = ActiveSheet.Range("A1:C3").Value2 End Sub
When using this method, the created array will always contain two-dimensions (just like the rows and column from the range). So, even if the source range is a single row or column, the array will still contain two-dimensions.
Convert arrays to string and ranges
Having got an array, we can then convert it into either a string or display the values in a range.
Convert array to string
The following code creates an array, then uses the Join function to convert it into a string.
Sub JoinArrayIntoString() Dim arr As Variant Dim joinedString As String 'Create an array arr = Array("Alpha", "Bravo", "Charlie") 'Turn array into a string, each item separated by a comma joinedString = Join(arr, " ,") End Sub
Convert array to range
A 2-dimensional array can be written to the cells in a worksheet in either a horizontal or vertical direction.
Sub WriteArrayToRange() Dim arr As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Write array across columns ActiveSheet.Range("D1:H1") = arr 'Alternative, write an array down rows 'ActiveSheet.Range("D1:D5") = Application.Transpose(arr) End Sub
Looping through each element in an array
There are two ways to loop through the elements of an array:
- For loop – Using the LBound and UBound functions to determine the number of times to loop
- For Each loop – Loops through every item in the array
NOTE – The For Each loop can only read the elements in an array; it cannot be used to change the values assigned to elements.
For loop: single-dimension array
The following example creates a single dimension array, then loops through each element in the array.
Sub ForLoopThroughArray() Dim arr As Variant Dim i As Long arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Loop from the LowerBound to UpperBound items in array For i = LBound(arr) To UBound(arr) MsgBox arr(i) Next i End Sub
For loop: multi-dimension array
A For loop can also be used for multi-dimension arrays, as shown in the code below.
Sub ForLoopThrough2DimensionArray() Dim arr(1 To 3, 1 To 3) As String Dim i As Long Dim j As Long arr(1, 1) = "Alpha" arr(1, 2) = "Apple" arr(1, 3) = "Ant" arr(2, 1) = "Bravo" arr(2, 2) = "Ball" arr(2, 3) = "Bat" arr(3, 1) = "Charlie" arr(3, 2) = "Can" arr(3, 3) = "Cat" For i = LBound(arr) To UBound(arr) For j = LBound(arr, 2) To UBound(arr, 2) MsgBox arr(i, j) Next j Next i End Sub
For Each loop: single-dimension array
The For Each loop works on a single or multi-dimension array. However, it can only read data from an array, it cannot assign values to an array.
Sub ForEachLoopThroughArray() Dim arr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Loop through array using For Each method For Each arrElement In arr MsgBox arrElement Next arrElement End Sub
For Each loop: multi-dimension array
The example below is to illustrate that the For Each loop is identical for both single and multi-dimension arrays.
Sub ForEachLoopThrough2DimensionArray() Dim arr(1 To 3, 1 To 3) As String Dim arrElement As Variant arr(1, 1) = "Alpha" arr(1, 2) = "Apple" arr(1, 3) = "Ant" arr(2, 1) = "Bravo" arr(2, 2) = "Ball" arr(2, 3) = "Bat" arr(3, 1) = "Charlie" arr(3, 2) = "Can" arr(3, 3) = "Cat" 'Loop through array For Each arrElement In arr MsgBox arrElement Next arrElement End Sub
Check if a value is in an array
We often need to search an array to discover if an item exists. The following is a reusable function for searching through an array for a specific value.
The result of the function can be:
- True = The value searched is in the array
- False = The value searched is not in the array
The function takes two arguments (1) the array and (2) the value to find.
Function IsValueInArray(arr As Variant, find As Variant) As Boolean Dim arrElement As Variant 'Loop through array For Each arrElement In arr If arrElement = find Then IsValueInArray = True Exit Function End If Next arrElement IsValueInArray = False End Function
The following is an example of how to call the function above; it tells the function to search for the string “Bravo” within the array. The result returned is True if found, or False if not.
Sub UseFunctionValueInArray() Dim arr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") MsgBox IsValueInArray(arr, "Bravo") End Sub
Find the index of an element in an array
In the previous sections we returned True of False depending on if an item exists. But often that is not enough, we want to know where it is in the array. The following is a reusable function which finds a value in an array, then returns the index position:
The result of the function can be:
- Number returned = The index position of the searched value
- False = The value searched was not found
The function takes two arguments the value to find and the array to search.
Function PositionInArray(arr As Variant, find As Variant) As Variant Dim i As Long For i = LBound(arr) To UBound(arr) If arr(i) = find Then PositionInArray = i Exit Function End If Next i PositionInArray = False End Function
The following shows how to use the function above; if the string “Bravo” is found within the array, it will return the index position, or False if not found.
Sub UseFunctionPositionInArray() Dim arr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") MsgBox PositionInArray(arr, "Bravo") End Sub
Resizing an array
As we’ve seen above, dynamic arrays are declared without a size. Then later in the code, ReDim is used to size the array. ReDim can be used many times during the macro to resize a dynamic array.
Static arrays cannot be resized, trying to do so, leads to an error.
When resizing an array with ReDim, the assigned values will be cleared out. To keep the existing values we must use the ReDim Preserve command.
Resize and blank values
The macro below creates, then resizes an array. After that, the code loops through the array to demonstrate that folowing a ReDim the the values are cleared.
Sub ResizeArraySize() Dim arr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Array will resize by lose all previous values ReDim arr(0 To 5) 'Loop through array using For Each method - all elements blank For Each arrElement In arr MsgBox arrElement Next arrElement End Sub
Resize array and keep existing values
The following macro creates, then resizes an array using ReDim Preserve. As the For Each loop demonstrates, by using ReDim Preserve, the values are maintained.
Sub ResizeArraySizeKeepValues() Dim arr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Array will resize by lose all previous values ReDim Preserve arr(0 To 5) 'Add additional value into the array arr(5) = "Foxtrot" 'Loop through array using For Each method - all elements blank For Each arrElement In arr MsgBox arrElement Next arrElement End Sub
Sorting array order
The following function sorts an array alphabetically. The function takes a single argument, the array to be sorted.
Function SortingArrayBubbleSort(arr As Variant) Dim i As Long Dim j As Long Dim temp As Variant For i = LBound(arr) To UBound(arr) - 1 For j = i + 1 To UBound(arr) If arr(i) > arr(j) Then temp = arr(j) arr(j) = arr(i) arr(i) = temp End If Next j Next i SortingArrayBubbleSort = arr End Function
The following is an example of how to use the function above.
Sub CallBubbleSort() Dim arr As Variant arr = Array("Charlie", "Delta", "Bravo", "Echo", "Alpha") arr = SortingArrayBubbleSort(arr) End Sub
Reverse array order
The function below reverses the order of an array. The function takes the name of an array as the only argument.
Function ReverseArray(arr As Variant) Dim temp As Variant Dim i As Long Dim arrSize As Long Dim arrMid As Long arrSize = UBound(arr) arrMid = (UBound(arr) - LBound(arr)) 2 + LBound(arr) For i = LBound(arr) To arrMid temp = arr(arrSize) arr(arrSize) = arr(i) arr(i) = temp arrSize = arrSize - 1 Next i ReverseArray = arr End Function
The code below is an example of how to use the function above.
Sub CallReverseArray() Dim arr As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") arr = ReverseArray(arr) End Sub
Filter an array
Along with LBound, UBound, Split and Join, another useful built-in function is Filter.
The Filter function returns an array that includes only the elements which contain a sub-string. In the example below the filteredArr array only includes the elements which contain the letter “o”,
Sub FilterArray() Dim arr As Variant Dim filteredArr As Variant Dim arrElement As Variant arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo") 'Filter array for any elements with the letter "o" filteredArr = Filter(arr, "o") 'Loop through the filtered array For Each arrElement In filteredArr MsgBox arrElement Next arrElement End Sub
The Filter function has 4 arguments:
Filter(SourceArray, Match, [Include], [CompareType])
- SourceArray – the original array
- Match – the substring to match
- Include (default is True if the argument is excluded)
- True = include the matched items
- False = exclude the matched items
- CompareType Include (default is 0 if the argument is excluded):
- 0 = vbBinaryCompare – The match is case sensitive
- 1 = vbTextCompare – The match is not case sensitive
Conclusion
Hopefully, this post covers most of your needs. However, VBA arrays are a vast topic, so make use of online forums to ask specific questions which this post doesn’t answer.
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
Key Points
- Think of an array in VBA array as a mini database to store and organized data (Example: student’s name, subject, and scores).
- Before you use it, you need to declare an array; with its data type, and the number of values you want to store in it.
If you want to work with large data using VBA, then you need to understand arrays and how to use them in VBA codes, and in this guide, you will be exploring all the aspects of the array and we will also see some examples to use them.
What is an Array in VBA?
In VBA, an array is a variable that can store multiple values. You can access all the values from that array at once or you can also access a single value by specifying its index number which is the position of that value in the array. Imagine you have a date with student’s name, subject, and scores.
You can store all this information in an array, not just for one student but for hundreds. Here’s a simple example to explain an array.
In the above example, you have an array with ten elements (size of the array) and each element has a specific position (Index).
So, if you want to use an element that is in the eighth position you need to refer to that element using its index number.
The array that we have used in the above example is a single-dimension array. But ahead in this guide, we will learn about multidimensional arrays as well.
How to Declare an Array in VBA
As I mentioned above an array is the kind of variable, so you need to declare it using the keywords (Dim, Private, Public, and Static). Unlike a normal variable, when you declare an array you need to use a pair of parentheses after the array’s name.
Let’s say you want to declare an array that we have used in the above example.
Steps to declare an array.
Full Code
Sub vba_array_example()
Dim StudentsNames(10) As String
StudentsNames(0) = "Waylon"
StudentsNames(1) = "Morton"
StudentsNames(2) = "Rudolph"
StudentsNames(3) = "Georgene"
StudentsNames(4) = "Billi"
StudentsNames(5) = "Enid"
StudentsNames(6) = "Genevieve"
StudentsNames(7) = "Judi"
StudentsNames(8) = "Madaline"
StudentsNames(9) = "Elton"
End Sub
Quick Notes
- In the above code, first, you have the Dim statement that defines the one-dimensional array which can store up to 10 elements and has a string data type.
- After that, you have 10 lines of code that define the elements of an array from 0 to 9.
Array with a Variant Data Type
While declaring an array if you omit to specify the data type VBA will automatically use the variant data type, which causes slightly increased memory usage, and this increase in memory usage could slow the performance of the code.
So, it’s better to define a specific data type when you are declaring an array unless there is a need to use the variant data type.
Returning Information from an Array
As I mentioned earlier to get information from an array you can use the index number of the element to specify its position. For example, if you want to return the 8th item in the area that we have created in the earlier example, the code would be:
In the above code, you have entered the value in cell A1 by using item 8 from the array.
Use Option Base 1
I’m sure you have this question in your mind right now why we’re started our list of elements from zero instead of one?
Well, this is not a mistake.
When programming languages were first constructed some carelessness made this structure for listing elements in an array. In most programming languages, you can find the same structure of listing elements.
However, unlike most other computer languages, In VBA you can normalize the way the is index work which means you can make it begins with 1. The only thing you need to do is add an option-based statement at the start of the module before declaring an array.
Now this array will look something like the below:
Searching through an Array
When you store values in an array there could be a time when you need to search within an array.
In that case, you need to know the methods that you can use. Now, look at the below code that can help you to understand how to search for a value in an array.
Sub vba_array_search()
'this section declares an array and variables _
that you need to search within the array.
Dim myArray(10) As Integer
Dim i As Integer
Dim varUserNumber As Variant
Dim strMsg As String
'This part of the code adds 10 random numbers to _
the array and shows the result in the _
immediate window as well.
For i = 1 To 10
myArray(i) = Int(Rnd * 10)
Debug.Print myArray(i)
Next i
'it is an input box that asks you the number that you want to find.
Loopback:
varUserNumber = InputBox _
("Enter a number between 1 and 10 to search for:", _
"Linear Search Demonstrator")
'it's an IF statement that checks for the value that you _
have entered in the input box.
If varUserNumber = "" Then End
If Not IsNumeric(varUserNumber) Then GoTo Loopback
If varUserNumber < 1 Or varUserNumber > 10 Then GoTo Loopback
'message to show if the value doesn't found.
strMsg = "Your value, " & varUserNumber & _
", was not found in the array."
'loop through the array and match each value with the _
the value you have entered in the input box.
For i = 1 To UBound(myArray)
If myArray(i) = varUserNumber Then
strMsg = "Your value, " & varUserNumber & _
", was found at position " & i & " in the array."
Exit For
End If
Next i
'message box in the end
MsgBox strMsg, vbOKOnly + vbInformation, "Linear Search Result"
End Sub
- In the first part of the code, you have variables that you need to use in the code further.
- After that, the next part is to generate random numbers by using RND to get you 10 values for the array.
- Next, an input box to let enter the value that you want to search within the array.
- In this part, you have a code for the string to use in the message box if the value you have entered is not found.
- This part of the code uses a loop to loop through each item in the array and check if the value that you have entered is in the array or not.
- The last part of the code shows you a message about whether a value is found or not.