Excel VBA Array – The Complete Guide

VBA Arrays

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.

In the first section, we will look at is what exactly is the VBA Array. You may not understand some of the code in the first section. Don’t worry. I will be breaking it all down into simple terms in the sections that come after.

The first section below provides a quick reference guide to using the VBA Array.  Come back to it anytime you need a quick reminder about how parts of the VBA Array work.

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 fuctionality than the Collection.
VBA Dictionary – Allows storing a Key\Value pair. Very useful in many applications.

The Microssoft guide for VBA Arrays can be found here.

A Quick Guide to the VBA Array

TaskStatic ArrayDynamic Array
DeclareDim arr(0 To 5) As Long Dim arr() As Long
Dim arr As Variant
Set SizeSee Declare aboveReDim 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 OnlyReDim Preserve arr(0 To 6)
Set valuesarr(1) = 22arr(1) = 22
Receive valuestotal = arr(1)total = arr(1)
First positionLBound(arr)LBound(arr)
Last positionUbound(arr)Ubound(arr)
Read all items(1D)For i = LBound(arr) To UBound(arr)
Next i

For i = LBound(arr,1) To UBound(arr,1)
Next i
For i = LBound(arr) To UBound(arr)
Next i

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 itemsDim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Pass to SubSub MySub(ByRef arr() As String)Sub MySub(ByRef arr() As String)
Return from FunctionFunction 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 FunctionDynamic onlyDim arr() As Long
Arr = GetArray()
Erase arrayErase arr
*Resets all values to default
Erase arr
*Deletes array
String to arrayDynamic onlyDim arr As Variant
arr = Split("James:Earl:Jones",":")
Array to stringDim sName As String
sName = Join(arr, ":")
Dim sName As String
sName = Join(arr, ":")
Fill with valuesDynamic onlyDim arr As Variant
arr = Array("John", "Hazel", "Fred")
Range to ArrayDynamic onlyDim arr As Variant
arr = Range("A1:D2")
Array to RangeSame 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:

VBa Arrays

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:

VBA Arrays



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:

  1. Static – an array of fixed length.
  2. 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.


Declaring the VBA Array

A static array is declared 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


VBA Arrays

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


VBA Array 2

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.


Get the 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 item 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

    Exit Function
    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)


Arrays VBA

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 three elements:

    Dim s As String
    s = "Red,Yellow,Green,Blue"

    Dim arr() As String
    arr = Split(s, ",")


Arrays VBA

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

    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”.

VBA Preserve

Before ReDim Preserve



VBA 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
    Do While vCentreVal < arr(lTempHi) And lTempHi > first
      lTempHi = lTempHi - 1
    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
  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.

VBA Array Dimension

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:

VBA Arrays

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


VBA 2D Array

Sample Student data


VBA 2D Array Output

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.


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 length of the array is always the same.
  6. Dynamic arrays allow you to determine the length 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 multidimensional 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 its 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.



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 and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)



  1. Is it possible to export multiple sheet ranges into one pdf?

    sheets(“deal log”).range(“deal_printview”)

    I need these three ranges to save as 1 PDF file pages 1, 2 and 3


    1. You can print each sheet to separate pdf files and then merge them (you can search for a code for merging). You do need pdf writers for it, I think.
      You can also combine all the sheets on a single (temp) sheet and print to pdf from there.

  2. Hi,
    An array created based on a range has at least 2 dimensions, even if only 1 column is involved
    example : arr = range(“A1:A4”) … which is not convenient for further operations.
    Is it possible to copy only 1 dimension into a new a array without looping on each item ?


  3. Hello. Excellent article.
    Talking about dynamic arrays, I would like to understand:
    A) what does it mean when Ubound = -1
    B) what is the difference between this state and the state when the array is declared.

    Thank you very much in advance.

    1. UBound should never be -1 unless the array was defined as something like arr(-5 to -1). I can’t think of any reason to do this.

  4. Hello! Excellent article Mr Kelly. I built an array by using your method. I have a question. For instance, I have this : location 1 : R; 2 : nothing; 3 : nothing; 4 : R. I have four locations and two R’s. Is it possible to know with an array function that is the second R has been suppressed? The result should be two. Thank you!

    1. Hi Frederick,

      You can use the worksheet.Count function for any overall total of items. Otherwise you have to check the array locations individually.

  5. Hi professor,
    Thank you for the helpful post
    I need to create an array which will take a list from the excel, add “option1”, “option2”, “option3” etc next to each of the items on the list and then paste it in a body of an email. Is that possible? if yes could you please give me some direction

  6. Hello Paul,
    I have a question concerning lists and treatment:
    is there a map or zip function ?? to treat every element of a list instead of :

    something like a: function addTwo() -> ListElement*2
    and a: zip(addTwo(), List)

    Thanks in advance. 😉

  7. Hi Sir,
    How can I drop elements from an array. Like in one loop i want it as {3,1,5,4,5,6,5,2,1,8}
    and then i need to drop 3,1,5 and get {4,5,6,5,2,1,8}

    1. If you want to remove elements you are better off using a collection. To remove elements from an array is not simple. You need to create a new array and copy elements there.

  8. Hi
    Thanks for the article. I have a problem with arrays. I am going to search 1 spreadsheet for the values in the other spreadsheet and do something when data are found. I don’t use vlookup function because it is very slow.
    UpdateRange array is very big (over 5000 cells sometimes) and it takes quite a long time to search it.
    However I need to search only last 1000 of cells/objects, but I have no idea how to write the code for that.
    I should start with:
    If UpdateRange.Count > 1000 than
    ‘ set update range as last 1000 cells/objects in range
    End if
    Below fragment of the code:

    Set ws1 = Worksheets(“spreadsheet1”)
    Set ws2 = Worksheets(“spreadsheet2”)
    lR1 = ws1.Range(“E” & Rows.Count).End(xlUp).Row
    lR2 = ws2.Range(“E” & Rows.Count).End(xlUp).Row
    Set UpdateRange = ws1.Range(“E2:E” & lR1)
    Set DataRange = ws2.Range(“E2:E” & lR2)

    For Each aCell In UpdateRange

    x = x + 1
    y = UpdateRange.Count
    prog = x / y

    Set bCell = DataRange.Find(What:=aCell, LookIn:=xlValues, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    If Not bCell Is Nothing Then
    With aCell.Interior
    .Pattern = xlNone
    .TintAndShade = 0
    .PatternTintAndShade = 0
    End With
    With aCell.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
    .PatternTintAndShade = 0
    End With
    End If
    With UserForm1
    .FrameProgress.Caption = Format(prog, “0%”)
    .LabelProgress.BackColor = 255
    .LabelProgress.Width = prog * (.FrameProgress.Width – 10)
    .Label2.Caption = “Searching for SENTs”
    End With


    1. Hi Robert,

      You can get the range by counting 1000 from the last row i.e IR1

      startrow = lR1 - 1000 + 1
      Set UpdateRange = ws1.Range("E" & startrow & ":E" & lR1)
  9. I made 8 laminated sheets for a treasure hunt but forgot in which order I put them… 🙁
    The mathematical steps are:
    [:4] (devide by four)
    [x3/5] (multiply with three fifth)
    [x7] (multiply with 7)
    [x5] (multiply with 5)
    [-2017] (substract 2017)
    [-50] (substract 50)
    [+23] (add 23)
    [+17] (add 17)

    If I have to try all permutations, there are over 40,000 options. What I know is that:
    ~ in all the steps between the starting number (1108) and solution (902), there are no negative numbers and no fractions;
    ~ Somewhere in the steps, [365] is an answer/sub-solution;
    ~ All 8 steps are used.

    I have no clue how to solve this with VBA. I tried to solve it by calculating steps from the starting number, solution and sub-solution, but stopped after 325 different calculations.
    Do you know a method to solve this problem?
    Any help is appreciated 🙂

  10. Hey There!
    I have one of those questions.

    I have used:
    ‘ Read values into array from first row
    Dim StudentMarks As Variant
    StudentMarks = Range(“A1:Z20000”).Value

    to load a huge sheet into an array. It is insanely fast.
    What I would like to do is a MATCH.

    I = match(“string to find”, StudentMarks(1), 0)
    IF this worked, I could avoid using a script.dictionary.
    IS there any method/function/way to do this??

    Alternatively, is there a way to bulk load a script.dictionary?
    The performance for ~ 100,000 rows was very fast. (less than 10 seconds)
    But loading 1,000,000 rows into the dictionary took 10 minutes.

    For that Want of a REAL hash table method.

    thanks, you articles have been amazing and clear

    1. Hi Peter,

      You can use Match with an array like this

      Dim arr As Variant
      arr = Sheet1.Range("A1:Z20000").Value
      Debug.Print WorksheetFunction.Match("string to find", arr, 0)

      You can use a HashTable like this

      Dim ht As Object
      Set ht = CreateObject("System.Collections.HashTable")
      ht("Apple") = 15
      ht("Orange") = 24
      Debug.Print ht("Apple")
  11. thanks!
    it is funny how many different things that we try FIRST until we give up and then post a question.
    I will have to dig into HastTable object to see what its performance is like.
    Using Script.Dictionary, is suffers greatly while adding a million keys.

    thanks again

  12. Dear Paul,
    Your tutorials are quite clean and lucid for even a beginner. They create interest and help to understand the topic.
    Thank you very much for the good work and providing it for free.
    -Pawan Joshi

  13. Hi
    I have a big array with values, i read from different files, then i dump it int a “master-file”.
    Now: I want to update those values.
    What I CAN do is just to read all and dump all again (slow and somehow stupid)
    What I can ALSO do is to check which files have changed since my last update, and only read from those files. Leaving me with an array filled mostly with 0s and the data that chaned. (GOOD)
    NOW what I can NOT do is to write that array; only where it is non zero… (SAD)
    Again: What I would like to do is to overwrite cells in a range the size of an sparsly filled array without overwriting the cells where the array containes a zero. (I guess i could loop through all rows and colums an check if the value is zero and only write if that’s not the case…. but i have a feeling that’s not how it schould be done)

    How schould i do this more efficently?

    THX for support

    1. Hi Flavio,

      I can’t think of any easier way that checking each value individually. There may be some way to do it using bit operations but there isn’t a simple way.


  14. HI, I’m trying to do an array like this:
    nclassi = Range(“E2”)
    Dim zik(0 To nclassi – 1) As Integer

    where Range(“E2”) is a number that can change.
    But Vba gave me an error cause it wants a costant instead of “nclassi-1”.
    Is there a way to correct this?

    1. You can do it like this.

      Note that the first Dim isn’t required but it is good practice to include it.

      nClassi = Range("E2") - 1
      Dim zik() As Integer
      ReDim zik(0 To nClassi) As Integer
  15. Can you change your main image on this page?!?? Your site is coming up frequently in my array syntax searches, and I always end up going to the bakery and += 2000 calories after I find what i’m looking for! Thanks!

  16. Hi Paul, congratulations on the excellent article. the best I’ve read about the subject. I have a macro that is building an array. The array has 400 columns and 1000 rows. I need outliers identified from each data column, not the total data cloud. I have to post the data in the worksheet first and then do the calculation. I’m using the code below. The code calculates the values in the worksheet. But it takes too long to calculate. I need to speed up the code, but I can not find the correct syntax. I’d like to first calculate in the array and then throw them in the worksheet. Is it possible? Thank you for your support.

    Sub outliers()
    Dim dblAverage As Double, dblStdDev As Double
    Dim rData As Range, rTest As Range, Rng As Range
    Set rData = Range(“B2:OK1001”)
    For Each rTest In rData.Columns
    dblAverage = WorksheetFunction.Average(rTest)
    dblStdDev = WorksheetFunction.StDev(rTest)
    Debug.Print dblAverage
    For i = 1 To rTest.Cells.Count
    Set Rng = rTest.Cells(i, 1)
    ‘Debug.Print Rng.Address
    If Rng “” Then
    If Rng > dblAverage + 1 * dblStdDev Or Rng < dblAverage – 1 * dblStdDev Then
    Rng.Value = "Outlier"
    End If: End If
    Next i: Next
    End Sub

  17. Paul;
    Your tutorial on arrays has been very helpful for my limited skill level. This code below works without error however my row count for the application can get upwards of 300,000 which i find takes about 6 secs to compete. This is by far will better than i had previously but in an effort to optimize further might you have any suggestions on how i might make this more efficient? Thank you in advance.
    ….snippet where most all the work is done…..

    Last_Row = Cells(Rows.Count, 1).End(xlUp).Row ‘ find the last row of Tic date

    ValArray = Range(“A7:E” & Last_Row).Value ‘array is 5 fields wide with length/rows from 30k, 300k in count

    Dim x As Long
    For x = LBound(ValArray) To UBound(ValArray) ‘loop through array to calculate 5th column value from col 2 vale
    LevelOne = ValArray(x, 2)

    ticrnd = Application.WorksheetFunction.RoundDown(valuereading, 0)
    BlkSize = Valuelevel * 100
    ValArray(x, 5) = (Ticrnd* (BlkSize – ticrnd) )/LevelOne
    Next x

    Range(“A7:E” & Last_Row).Value = ValArrayArray ‘ repost array back in to worksheet

    SecondsElapsed = Round(Timer – startime, 2) ‘my timer to test code speed.
    MsgBox “This code ran successfully in ” & SecondsElapsed & ” seconds”, vbInformation

  18. Hello,

    My below code works in row 2 only. Is there a way for the same logic to be be applied to rows 3-5000 without having to copy and paste the IF/Thens an change the row numbers?

    Lastly, the value for “D2” is {=INDEX(SHEET1!$B:$B,MATCH(SHEET2!A2&B2,SHEET1!$C:$C&SHEET1!$D:$D,0))}
    How do you program a macro to read an array’s value?

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Not (Application.Intersect(Target, Range(“D2:D2000”)) _
    Is Nothing) Then
    If Range(“D2”) = “Start Process” Then
    Range(“E2”) = Now()
    End If
    If Range(“D2”) = “Complete” Then
    Range(“F2”) = Now()
    End If
    End If
    End Sub

  19. in the section before Types of VBA Arrays, don’ t we need to use .value2 to assign value to array

    ‘ assign value to variable
    Student1 = .Cells(1, 1) /////in stead of .cells(1,1).value2 is it the same ?

    ‘ assign value to first item in array
    Students(1) = .Cells(1, 1) /////in stead of .cells(1,1).value2 is it the same ?

    if .value2 is neglectable , then will it faster to neglect it?
    thank you so much

  20. Hi. First of all, Thank you for this detailed explanation.

    Based on the idea of using ‘For Each’ Loop on an Array I created a function, where the Array contains the list of all the cells I want to perform a specific procedure.
    However, when I run the code, some of the cells are skipped. While I confirmed that the array itself contains the cell ranges, the function seems to skip them. COuld you please help me with this problem ?

  21. Sub RangeToArray()
    Dim ref As Worksheet
    Dim myary As Variant
    Set ref = ThisWorkbook.Sheets(“Reference”)
    myary = ref.Range(ref.Cells(2, 22), ref.Cells(2, 25)).Value
    Debug.Print myary(0)
    End Sub

    what is wrong in the code. I wish to print the contents of the array.

  22. Hello Paul, and thanks for such a comprehensive coverage of VBA arrays in Excel.
    I’ve read through most of the document but have a few queries.

    You say (talking of static arrays):
    ‘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.’
    You cannot use ReDim on static arrays.
    (Typo: “used ReDim” instead of “use ReDim”)

    You say: “When we use Redim Preserve the new array must be bigger and start at the same dimension”, and:
    ‘We cannot Preserve from (0 to 2) to (0 to 1) or (0) as they are smaller than original array.’
    You *can* reduce the UBound of the final dimension with Preserve. The relevant values are discarded.
    (There are also a couple of punctuation errors: “it’s” instead of “its”)

    The paragraph before Sub Preserve2DError() says:
    ‘In the following code we use Preserve on the lower bound. Running this code will give the “Subscript out of range” error:’
    The example uses Preserve on the *upper* bound of the first dimension (which is also illegal).

    Excel treats 1-dimensional arrays as horizontal, i.e. as a row. A 1-D array has to be transposed to be written to a column. You write:
    ‘If you think of a single spreadsheet column as a single dimension then more than one column is two dimensional.’, and:
    ‘So you can think of 1 dimensional being rows only and 2 dimensional as being rows and columns.’

    I think this should say:
    ‘If you think of a single spreadsheet row as a single dimension then more than one row is two dimensional.’, and:
    ‘So you can think of 1 dimensional being columns only…’

    You say:
    ‘Using the For Each loop gives us the array in one order only – from LBound to UBound’
    I think this would be more informative if it read something like:
    ‘Using the For Each loop gives us the array in the order from LBound to UBound working from the last dimension to the first dimension’.

    (One punctuation error: “it’s” instead of “its”)

    Thanks again for such good coverage. I’m looking forward to reading your other topics.
    Alan Olrog

  23. Hi, what would be a fast way to read data from A1:A10 range into 1D variable. Is it possible to read it first into 2D array – MyArr=Range(“A1:A10”).Value – an then somehow slash one dimension?

    1. You can use Application.WorksheetFunction.Index() to copy a row or column from an array. See example here.

      Keep in mind that it’s a very slow method.

  24. Hi! I am attempting to use & paste the results from **Public Sub ReadAndDisplay()** into an actual range in my workbook instead of simply printing. Printing to the immediate window works perfectly but i cant actually write a dynamic for loop to return the results to a range in my wore

    The difficult part is that instead of i and j, I have two vectors sitting right outside my array of values: i is equal to the letters A through F in a 6×1 array and j is a 1×5 array A through E which sits right outside of my values which are in a 6×5 array. Any suggestions?


    1. Hi Mark,

      You use i,j to read through the array but you use different variables to track the output.

      The code below writes to a sheet called sheet2 starting at cell B2.

      ' Print the array values
      Debug.Print "i", "j", "Value"
      Dim i As Long, j As Long, row As Long, column As Long
      ' start at b2
      row = 2
      For i = LBound(StudentMarks) To UBound(StudentMarks)
          column = 2
          For j = LBound(StudentMarks, 2) To UBound(StudentMarks, 2)
              Sheet2.Cells(row, column).Value2 = StudentMarks(i, j)
              column = column + 1
          Next j
          row = row + 1
      Next i
  25. Hi,
    I would like to know if I can reference an array’ s name by using other variable names concatenated together?
    Ex., variable names (year= yr2018, yr2019, yr2020) (weather=spring, summer, fall ) Foodtime= breakfast, lunch, dinner)
    Array names yr2018springbreakfast so reference this array like (year & weather & foodtime)(1 to 12,1 to 4) for instance
    trying to reference array using what ever value is in year, weather,

  26. Thanks for the interesting read, however I think you’re incorrect when you state that:
    ‘ 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”)

    I have tested this using 800,000 rows of data and it appears that copy/paste is faster (x5) than simply assigning the values. Here is my test code that shows it’s faster. Please run it and tell me when you think.

    Sub Time()
    ‘ Measure time for copying 2 large ranges of cells

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    Dim timer1 As Double
    Dim timer2 As Double
    Dim timer3 As Double
    Dim tmpTimer As Double

    ‘Assignment method
    tmpTimer = Timer
    Range(“C1:C893008”).Value = Range(“A1:A893008”).Value
    timer1 = Timer – tmpTimer

    ‘Normal copy and paste
    tmpTimer = Timer
    Range(“A1:A893008”).Copy Range(“E1:E893008”)
    timer2 = Timer – tmpTimer

    MsgBox “Assignment Method took: ” & timer1 & vbNewLine & _
    “Copy/Paste method took: ” & timer2

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
    End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *