The Complete Guide To Using Arrays in Excel VBA
The Complete Guide To Using Arrays in Excel VBA
Excel VBA
JANU ARY 6, 2015 BY PAU L KELLY ·9 4 COMMENTS
Or Or
For i = LBound(arr,1) To UBound(arr,1) For i = LBound(arr,1) To UBound(arr,1)
Next i Next i
Introduction
This post provides an in-depth look at arrays in the Excel VBA programming language. It covers the important points
such as
In the first section we will look at is what are arrays and why you need them. You may not understand some of the code in
the first section. This is fine. I will be breaking it all down into simple terms in the following sections of the post.
Quick Notes
Sometimes Collections are a better option than arrays. You may want to check out my post The Ultimate Guide To
Collections in Excel VBA.
Arrays and Loops go hand in hand. The most common loops you use with arrays are the For Loop and the For Each
Loop(read-only).
The following example shows a variable being used to store the marks of a student.
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
With ThisWorkbook.Worksheets("Sheet1")
Student1 = .Range("C2").Offset(1)
Student2 = .Range("C2").Offset(2)
Student3 = .Range("C2").Offset(3)
Student4 = .Range("C2").Offset(4)
Student5 = .Range("C2").Offset(5)
Debug.Print Student1
Debug.Print Student2
Debug.Print Student3
Debug.Print Student4
Debug.Print Student5
End With
End Sub
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
Dim i As Integer
For i = 1 To 5
Students(i) = .Range("C2").Offset(i)
Next i
Debug.Print Students(i)
Next i
End With
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
' Array
Student1 = .Cells(1, 1)
Students(1) = .Cells(1, 1)
Debug.Print Student1
Debug.Print Students(1)
The difference between these arrays mainly in how they are created. Accessing values in both array types is exactly the
same. In the following sections we will cover both types.
Declaring an Array
A static array is declared as follows
' Create array with locations 2,3,4 ' This is rarely used
End Sub
An Array of 0 to 3
As you can see the size is specified when you declare a static array. The problem with this is that you can never be sure in
advance the size you need. Each time you run the Macro you may have different size requirements.
If you do not use all the array locations then the resources are being wasted. If you need more locations you can
used ReDim but this is essentially creating a new static array.
The dynamic array does not have such problems. You do not specify the size when you declare it. Therefore you can then
grow and shrink as required
' Set the size 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 size. With a static array you have to give the size up front.
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 size. With a static array you must set the size to the largest possible
number of students.
Need Help Using Arrays? Click here to get your FREE Cheat Sheet
arrMarks(0) = 5
arrMarks(3) = 46
arrMarks(4) = 99
End Sub
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 three elements.
Dim s As String
s = "Red,Yellow,Green,Blue"
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.
The following example assigns random numbers to an array using a loop. It then prints out these numbers using a second
loop.
Dim i As Long
arrMarks(i) = 5 * Rnd
Next i
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 size.
The real benefit is that if the size 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 size as long as you use these functions.
In the following code the value of mark changes but it does not change the value in the array.
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.
Debug.Print mark
Next mark
Using Erase
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 of integers 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.
Lets 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.
Dim i As Long
arrMarks(i) = 5 * Rnd
Next i
Erase arrMarks
' Print out the values - there are all now zero
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.
ReDim arrMarks(0 To 3)
Dim i As Long
arrMarks(i) = 5 * Rnd
Next i
Erase arrMarks
End Sub
Sub UsingRedim()
ReDim arr(0 To 2)
arr(0) = "Apple"
ReDim arr(0 To 3)
End Sub
If we want to extend the size of an array without losing the contents, we can use the Preserve keyword.
When we use Redim Preserve the new array must be bigger and start at the same dimension e.g.
We cannot Preserve from (0 to 2) to (1 to 3) or (2 to 10) as they are different starting dimensions.
We cannot Preserve from (0 to 2) to (0 to 1) or (0) as they are smaller than original array.
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 size of the array so we don’t lose the original contents.
Sub UsingRedimPreserve()
ReDim arr(0 To 2)
arr(0) = "Apple"
arr(1) = "Orange"
arr(2) = "Pear"
End Sub
You can see from the screenshots below, that the original contents of the array have been “Preserved”.
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 many want to considering using a Collection.
Passing an Array to a Sub or Function
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.
UseArray arr
End Sub
Debug.Print UBound(arr)
End Function
arr = GetArray
End Sub
GetArray = arr
End Function
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(2 dimensional) you need to give the row AND the column. So you can think of 1 dimensional
being rows only and 2 dimensional as being rows and columns.
Note: It is possible to have more 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.
The following example creates a random value for each item in the array and the prints the values to the Immediate
Window.
Next j
Next i
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.
You may notice that LBound and UBound have a second argument of 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.
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
Debug.Print "Value"
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.
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.
Dim rg As Range
Set rg = ThisWorkbook.Worksheets("Sheet1").Range("C3:E6")
StudentMarks = rg.Value
Debug.Print i, j, StudentMarks(i, j)
Next j
Next i
End Sub
Sample Student 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).
For example, the following code would be much faster than the code below it
StudentMarks = Range("A1:Z20000").Value
Dim i As Long
StudentMarks(i, 1) = StudentMarks(i, 1) * 2
'...
Next i
Range("A1:Z20000").Value = StudentMarks
End Sub
Sub UsingCellsToUpdate()
Dim c As Variant
Next c
End Sub
Assigning from one set of cells to another is also much faster than using Copy and Paste
Range("A1:A10").Value = Range("B1:B10").Value
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
Conclusion
The following is a summary of the main points of this post
1. Arrays are an efficient way of storing a list of items of the same type.
2. You can access an array item directly using the number of the location which is known as the subscript or
index.
3. The common error “Subscript out of Range” is caused by accessing a location that does not exist.
4. There are two types of arrays: Static and Dynamic.
5. Static is used when the size of the array is always the same.
6. Dynamic arrays allow you to determine the size of an array at run time.
7. LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
8. The basic array is one dimensional. You can also have multi dimensional arrays.
9. You can only pass an array to a procedure using ByRef. You do this like this: ByRef arr() as long.
10. You can return an array from a function but the array, it is assigned to, must not be currently allocated.
11. A worksheet with it’s rows and columns is essentially a two dimensional array.
12. You can read directly from a worksheet range into a two dimensional array in just one line of code.
13. You can also write from a two dimensional array to a range in just one line of code.