Using arrays in vba excel

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:

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)

ImmediateWindow

ImmediateSampeText

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

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:

  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.

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

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.

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)

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 four 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

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

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

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.

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

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

What is VBA Arrays in Excel?

A VBA array in excel is a storage unit or a variable which can store multiple data values. These values must necessarily be of the same data type. This implies that the related values are grouped together to be stored in an array variable.

For example, a large organization which operates in several countries employs 10,000 people. To store the details of all employees, a database containing hundreds of rows and columns is created. So, either of the following actions can be performed:

  1. Create multiple variables to fetch the cell values and give them to the program.
  2. Create an array consisting of multiple related values.

The action “a” is far more complicated and time-consuming than action “b.” For this reason, we use VBA arrays.

To use an array variable, it needs to be declared or defined first. While declaring, the length of the array may or may not be included.

The purpose of using an array is to hold an entire list of items in its memory. In addition, with an array, it is not required to declare each variable to be fetched from the dataset.

The difference between an array and a regular variable of VBAIn VBA, «public variables» are variables that are declared to be used publicly for all macros written in the same module as well as macros written in different modules. As a result, variables declared at the start of any macro are referred to as «Public Variables» or «Global Variables.»read more is that the latter can hold a single value at a given time. Moreover, while using multiple regular variables, every variable needs to be defined prior to its usage.

Table of contents
  • What is VBA Arrays in Excel?
    • The Properties of VBA Arrays
    • The Working of a VBA Array
    • Types of VBA Arrays
      • #1 – Static Array
      • #2 – Dynamic Array
      • #3 – One-dimensional Array
      • #4 – Two-dimensional Array
      • #5 – Multi-dimensional Array
    • How to use Arrays in VBA?
    • The Procedure of Using an Array
    • The Cautions Governing the use of VBA Arrays
    • Frequently Asked Questions
    • Recommended Articles

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Arrays (wallstreetmojo.com)

The Properties of VBA Arrays

The properties of VBA arrays are listed as follows:

  • In an array, the data of the same type are grouped together. So, creating an array is similar to creating a separate memory unit which can hold data.
  • The array to be used must correspond with the kind of dataset. For instance, if the dataset has a single row or a single column, a one-dimensional array is used. A two-dimensional array is used if the dataset has multiple rows and columnsA cell is the intersection of rows and columns. Rows and columns make the software that is called excel. The area of excel worksheet is divided into rows and columns and at any point in time, if we want to refer a particular location of this area, we need to refer a cell.read more.
  • An array can function as static or dynamic. A dynamic array can include an infinite number of rows and columns. In contrast, a static array holds a limited number of rows and columns, which are defined at the time of creation.

Note: During run time, the size of a static array cannot be modified while a dynamic array can be resized.

The Working of a VBA Array

An array works similar to the mathematical rule of a matrix. This implies that an array identifies the data by its location.

For example, if the number 20 is required in cell B3, we write the location in the code as (3, 2). The number “3” represents the row number and “2” represents the column number.

In Excel, the code of locations is known as upper bound and lower bound. By default, the locations in Excel begin from 0 and not from 1. Hence, “A1” is considered as row number 0 and not as row number 1.

Likewise, columns also begin from 0 and not from 1.

Note: In the preceding example of cell B3, Excel counts the rows and columns from 1.

Arrays in VBA Excel 1

If we define this array as static, it cannot hold more than the defined variables. Hence, if the user is not sure about the number of values to be memorized by an array, it is advisable to use a dynamic array.

The data is entered in the array, as shown in the following image.

Arrays in VBA Excel 2

After storing data in an array, it is ready to be used as a variable in VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Types of VBA Arrays

The VBA arrays can be categorized as follows:

  1. Static array
  2. Dynamic array
  3. One-dimensional array
  4. Two-dimensional array
  5. Multi-dimensional array

Let us consider every array one by one.

#1 Static Array

A static array has a fixed, pre-defined count of the values that can be stored in it. The code of a static array is written as follows:

Arrays in VBA Excel (Static Array)

#2 Dynamic Array

A dynamic array does not have a pre-defined count of values that can be stored in it. The code of a dynamic array is written as follows:

Arrays in VBA Excel Dynamic Array).

#3 One-dimensional Array

A one-dimensional array can hold data either from a single row or a single column of Excel.

A table consists of the marks obtained by 5 students of a class. The Excel data and the code of a one-dimensional array are shown as follows:

Arrays in VBA Excel (One dimensional array)

Arrays in VBA Excel (One dimensional array) 1

#4 Two-dimensional Array

A two-dimensional array can store values from multiple rows and columns of Excel.

A table consists of marks obtained by two students in Mathematics and Science. The Excel data and the code of a two-dimensional array are shown as follows:

Arrays in VBA Excel (Two dimensional array)

Arrays in VBA Excel (Two dimensional array) 1

#5 Multi-dimensional Array

A multi-dimensional array can store data from multiple sheets which contain several rows and columns. An array can have a maximum of 60 dimensions.

A table consists of the marks obtained by two students in Mathematics, Science, and Accountancy. The Excel data and the code of a multi-dimensional array are shown as follows:

Arrays in VBA Excel (Multidimensional Array)

Arrays in VBA Excel (Multidimensional Array) 1

How to use Arrays in VBA?

You can download this Arrays in VBA Excel Template here – Arrays in VBA Excel Template

An array can be used in several situations. It is particularly used when there are a large number of variables to be declared and it is not feasible to define each and every variable.

The shortcut to open the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more is “Alt+F11.”

ALT + F11

Once the VBA editor opens, the code can be entered in “ThisWorkbook,” as shown in the following image.

VBA Editor in Excel

The Procedure of Using an Array

The steps of using an array are listed as follows:

Step 1: Choose the type of array. It can be either dynamic or static.

For a dynamic array, the dimension is defined as “variant.”

Step 1

For a static array, the dimension is defined as “static.”

Step 1-1

Step 2: Define the rows and columns to be stored in the array.

Enter “1” within the brackets, as shown in the following image. This implies that the array can hold the values of two rows. This is because Excel begins counting from 0.

Step 2

If rows and columns both are required, one needs to define them. So, enter “1 to 2” and “1 to 3” as arguments. The same is shown in the following image.

The argument “1 to 2” implies two rows and “1 to 3” implies three columns.

Note: In this case, Excel counts the rows and columns from 1 and not from 0.

Step 2-1

Step 3: Enter the data as input in the array.

The data is entered in the form of (i,j), where “i” represents the row and “j” represents the column. Since the data is entered cell-wise, “a (1,1)” implies cell A1.

Hence, 30 will be entered in cell A1.

Step 3

Step 4: Close the code.

Once the data for the array has been entered, the last step is to close the code. This is shown in the following image.

Step 4

The Cautions Governing the use of VBA Arrays

The cautions to be observed while creating VBA arrays are listed as follows:

  • Remember that by default, Excel counts the rows and columns beginning from zero. So, if “i” is 2, it implies three rows. The same applies to the column entries (j) as well.
  • Ensure that the data entered in the array begins from (0,0), i.e., the first row and the first column.
  • Use the “VBA REDIMThe VBA Redim statement increases or decreases the storage space available to a variable or an array. If Preserve is used with this statement, a new array with a different size is created; otherwise, the current variable’s array size is changed.read more” function to change the size of a dynamic array.
  • Use “integer” as the dimension of a two-dimensional array that accepts integer values.
  • Save the Excel file with the “.xlsm” extension otherwise, the VBA coding will not run the next time.

Frequently Asked Questions

1. Define VBA arrays.

A VBA array is capable of storing a series of data values. The condition is that all the values should be of the same data type. These values are known as the elements of an array.

For assigning values to an array, the location number of Excel is used. This number is known as the index or the subscript of an array. By default, the array index begins from zero unless an “Option Base 1” statement is entered at the beginning of the module.

With the “Option Base 1” statement, the array index begins from one.

Arrays are classified as follows:

• Static or dynamic based on whether the array size is fixed or changeable.
• One-dimensional, two-dimensional, or multi-dimensional based on the number of rows and columns of the source dataset from where values are assigned to an array.

2. Why are VBA arrays used?

An array is used for the following reasons:

• It helps avoid writing multiple lines of code. Since a regular variable can store a single value at a given time, each variable which is to be stored needs to be defined.
• It allows easy accessibility to the elements of the array. Every item of the array can be accessed with its row and column number which are specified while assigning values.
• It allows grouping the data of the same type. Since the related data is placed together, it simplifies working with large datasets.
• It adds the speed factor to working with Excel. Arrays make it easier to organize, retrieve, and alter data. This helps in improving productivity.

3. How to use the JOIN and SPLIT functions with respect to a VBA array?

The JOIN function combines several substrings of an array and returns a string. The JOIN function is the reverse of the SPLIT function.

The syntax of the JOIN function is stated as follows:

“Join(sourcearray,[delimiter])”

The arguments are explained as follows:

• Sourcearray: This is a one-dimensional array consisting of substrings to be joined.
• Delimiter: This is a character that separates the substrings of the output. If this is omitted, the delimiter space is used.

Only the argument “sourcearray” is required.

The SPLIT function divides the whole string into multiple substrings. It splits on the basis of the specified delimiter. It returns a one-dimensional and zero-based array.

The syntax of the SPLIT function is stated as follows:

“Split(expression,[delimiter,[limit,[compare]]])”

The arguments are explained as follows:

• Expression: This is the entire string which is to be split into substrings.
• Delimiter: This is a character like space, comma etc., that separates the substrings of the expression. If this is omitted, the space is considered as the delimiter.
• Limit: This is the number of substrings to be returned. It returns all the substrings if the limit is set at “-1.”
• Compare: This is the comparison method to be used. Either a binary (vbBinaryCompare) or textual comparison (vbTextCompare) can be performed.

Only the argument “expression” is required. The remaining arguments are optional.

Recommended Articles

This has been a guide to VBA Arrays. Here we discuss the different types of arrays, how to declare and use them. We also discussed the array in VBA examples. You can download the template from the website. You may also look at these useful Excel tools-

  • Top 4 Error VLOOKUPThe top four VLOOKUP errors are — #N/A Error, #NAME? Error, #REF! Error, #VALUE! Error.read more
  • VBA Books
  • VBA Array Function in excelArrays are used in VBA to define groups of objects. There are nine different array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND.read more

In this Article

  • VBA Array Quick Sheet
    • Arrays
  • VBA Array Quick Examples
  • Array Benefits? – Speed!
  • Create / Declare an Array (Dim)
    • Static Array
    • Dynamic Array
    • ReDim vs. ReDim Preserve
    • Declaring Arrays Simplified
  • Set Array Values
    • Get Array Value
  • Assign Range to Array
    • Output Array to Range
  • 2D / Multi-Dimensional Arrays
  • Multi-Dimensional Array Examples
    • 1D Array Example
    • 2D Array Example
    • 3D Array Example
  • Array Length / Size
    • UBound and LBound Functions
    • Array Length Function
  • Loop Through Array
    • For Each Array Loop
    • Loop Through 2D Array
  • Other Array Tasks
    • Clear Array
    • Count Array
    • Remove Duplicates
    • Filter
    • IsArray Function
    • Join Array
    • Split String into Array
    • Const Array
    • Copy Array
    • Transpose
    • Function Return Array
  • Using Arrays in Access VBA

In VBA, an Array is a single variable that can hold multiple values.  Think of an array like a range of cells: each cell can store a value. Arrays can be one-dimensional (think of a single column), two-dimensional (think of multiple rows & columns), or multi-dimensional.  Array values can be accessed by their position (index number) within the array.

VBA Array Quick Sheet

Arrays

Create

Dim arr(1 To 3) As Variant
arr(1) = “one”
arr(2) = “two”
arr(3) = “three”

Create From Excel

Dim arr(1 To 3) As Variant
Dim cell As Range, i As Integer
i = LBound(arr)
For
Each cell In Range(“A1:A3”)
i = i + 1
arr(i) = cell.value
Next cell

Read All Items

Dim i as Long
For i = LBound(arr) To UBound(arr)
MsgBox arr(i)
Next i

Array to String

Dim sName As String
sName = Join(arr, “:”)

Increase Size

ReDim Preserve arr(0 To 100)

VBA Array Quick Examples

Let’s look at a full example before we dive into specifics:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"

    msgbox strNames(3)
End Sub

Here we’ve created the one-dimensional string array: strNames with size four (can hold four values) and assigned the four values. Last we display the 3rd value in a Message Box.

In this case, the benefit of using an Array is small: only one variable declaration is required instead of four.

However, let’s look at an example that will show the true power of an array:

Sub ArrayExample2()
    Dim strNames(1 To 60000) As String
    Dim i As Long

    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
End Sub

Here we’ve created an Array that can hold 60,000 values and we’ve quickly populated the array from Column A of a worksheet.

Array Benefits? – Speed!

You might think of Arrays similar to Excel worksheets:

  • Each cell (or item in an array) can contain its own value
  • Each cell (or item in an array) can be accessed by its row & column position.
    • Worksheet Ex.  cells(1,4).value = “Row 1, Column 4”
    • Array Ex.  arrVar(1,4) = “Row 1, Column 4”

So why bother with Arrays?  Why not just read and write values directly to cells in Excel?  One word: Speed!

Reading / Writing to Excel cells is a slow process. Working with Arrays is much faster!

Create / Declare an Array (Dim)

Note: Arrays can have multiple “dimensions”. To keep things simple, we will start by only working with one-dimensional arrays. Later in the tutorial we will introduce you to multiple-dimension arrays.

Static Array

Static Arrays are arrays that cannot change size. Conversely, Dynamic Arrays can change size.  They are declared slightly differently. First, let’s look at static arrays.

Note: If your array won’t change in size, use a static array.

Declaring a static array variable is very similar to declaring a regular variable, except you must define the size of the array. There are several different ways to set the size of an array.

You can explicitly declare the start and end positions of an array:

Sub StaticArray1()

    'Creates array with positions 1,2,3,4
    Dim arrDemo1(1 To 4) As String
    
    'Creates array with positions 4,5,6,7
    Dim arrDemo2(4 To 7) As Long
    
    'Creates array with positions 0,1,2,3
    Dim arrDemo3(0 To 3) As Long

End Sub

Or you can enter only the array size:

Sub StaticArray2()

    'Creates array with positions 0,1,2,3
    Dim arrDemo1(3) As String

End Sub

Important! Notice that by default, Arrays start at position 0.  So Dim arrDemo1(3) creates an array with positions 0,1,2,3.

You can declare Option Base 1 at the top of your module so that the array starts at position 1 instead:

Option Base 1

Sub StaticArray3()

    'Creates array with positions 1,2,3
    Dim arrDemo1(3) As String

End Sub

However, I find that it’s much easier (and less confusing) to just explicitly declare the start and end positions of arrays.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Dynamic Array

Dynamic Arrays are arrays whose size can be changed (or whose size does not need to be defined).

There are two ways to declare a Dynamic Array.

Variant Arrays

The first way to declare a Dynamic Array is by setting the array to type Variant.

Dim arrVar() As Variant

With a Variant Array, you do not need to define the array size. The size will automatically adjust.  Just remember that the Array starts with position 0 (unless you add Option Base 1 to the top of your module)

Sub VariantArray()
    Dim arrVar() As Variant
    
    'Define Values (Size = 0,1,2,3)
    arrVar = Array(1, 2, 3, 4)
    
    'Change Values (Size = 0,1,2,3,4)
    arrVar = Array("1a", "2a", "3a", "4a", "5a")

    'Output Position 4 ("5a")
    MsgBox arrVar(4)

End Sub

Non-Variant Dynamic Arrays

With non-variant arrays, you must define the array size before assigning values to the array. However, the process to create the array is slightly different:

Sub DynamicArray1()
    Dim arrDemo1() As String

    'Resizes array with positions 1,2,3,4
    ReDim arrDemo1(1 To 4)
    
End Sub

First you declare the array, similar to the static array, except you omit the array size:

Dim arrDemo1() As String

Now when you want to set the array size you use the ReDim command to size the array:

'Resizes array with positions 1,2,3,4
ReDim arrDemo1(1 To 4)

ReDim resizes the array. Read below for the difference between ReDim and ReDim Preserve.

ReDim vs. ReDim Preserve

When you use the ReDim command you clear all existing values from the array.  Instead you can use ReDim Preserve to preserve array values:

'Resizes array with positions 1,2,3,4 (Preserving existing values)
ReDim Preserve arrDemo1(1 To 4)

Declaring Arrays Simplified

You might be feeling overwhelmed after reading everything above. To keep things simple, we will mostly work with static arrays for the rest of the article.

VBA Programming | Code Generator does work for you!

Set Array Values

Setting array values is very easy.

With a static array, you must define each position of the array, one at a time:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
End Sub

With a Variant Array you can define the entire array with one line (only practical for small arrays):

Sub ArrayExample_1Line()
    Dim strNames() As Variant

    strNames = Array("Shelly", "Steve", "Neema", "Jose")

End Sub

If you attempt to define a value for an array location that does not exist, you will receive a Subscript Out of Range error:

strNames(5) = "Shannon"

vba set array value

In the ‘Assign Range to Array’ section Below we’ll show you how to use a loop to quickly assign large numbers of values to arrays.

Get Array Value

You can fetch array values the same way.  In the example below we will write array values to cells:

    Range("A1").Value = strNames(1)
    Range("A2").Value = strNames(2)
    Range("A3").Value = strNames(3)
    Range("A4").Value = strNames(4)

Assign Range to Array

To assign a Range to an Array you can use a loop:

Sub RangeToArray()
    Dim strNames(1 To 60000) As String
    Dim i As Long

    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
End Sub

This will loop through cells A1:A60000, assigning the cell values to the array.

Output Array to Range

Or you can use a loop to assign an array to a range:

    For i = 1 To 60000
        Cells(i, 1).Value = strNames(i)
    Next i

This will do the reverse: assign array values to cells A1:A60000

2D / Multi-Dimensional Arrays

So far we’ve worked exclusively with single-dimensional (1D) arrays.  However, arrays can have up to 32 dimensions.

Think of a 1D array like a single row or column of Excel cells, a 2D array like an entire Excel worksheet with multiple rows and columns, and a 3D array is like an entire workbook, containing multiple sheets each containing multiple rows and columns (You could also think of a 3D array as like a Rubik’s Cube).

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Multi-Dimensional Array Examples

Now let’s demonstrate examples of working with arrays of different dimensions.

1D Array Example

This procedure combines the previous array examples into one procedure, demonstrating how you might use arrays in practice.

Sub ArrayEx_1d()
    Dim strNames(1 To 60000) As String
    Dim i As Long
 
    'Assign Values to Array
    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
    
    'Output Array Values to Range
    For i = 1 To 60000
        Sheets("Output").Cells(i, 1).Value = strNames(i)
    Next i
End Sub

2D Array Example

This procedure contains an example of a 2D array:

Sub ArrayEx_2d()
    Dim strNames(1 To 60000, 1 To 10) As String
    Dim i As Long, j As Long
 
    'Assign Values to Array
    For i = 1 To 60000
        For j = 1 To 10
            strNames(i, j) = Cells(i, j).Value
        Next j
    Next i
    
    'Output Array Values to Range
    For i = 1 To 60000
        For j = 1 To 10
            Sheets("Output").Cells(i, j).Value = strNames(i, j)
        Next j
    Next i
End Sub

3D Array Example

This procedure contains an example of a 3D array for working with multiple sheets:

Sub ArrayEx_3d()
    Dim strNames(1 To 60000, 1 To 10, 1 To 3) As String
    Dim i As Long, j As Long, k As Long
 
    'Assign Values to Array
    For k = 1 To 3
        For i = 1 To 60000
            For j = 1 To 10
                strNames(i, j, k) = Sheets("Sheet" & k).Cells(i, j).Value
            Next j
        Next i
    Next k
    
    'Output Array Values to Range
    For k = 1 To 3
        For i = 1 To 60000
            For j = 1 To 10
                Sheets("Output" & k).Cells(i, j).Value = strNames(i, j, k)
            Next j
        Next i
    Next k
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Array Length / Size

So far, we’ve introduced you to the different types of arrays and taught you how to declare the arrays and get/set array values. Next we will focus on other necessary topics for working with arrays.

UBound and LBound Functions

The first step to getting the length / size of an array is using the UBound and LBound functions to get the upper and lower bounds of the array:

Sub UBoundLBound()
    Dim strNames(1 To 4) As String
    
    MsgBox UBound(strNames)
    MsgBox LBound(strNames)
End Sub

Subtracting the two (and adding 1) will give you the length:

GetArrLength = UBound(strNames) - LBound(strNames) + 1

Array Length Function

Here is a function to get a single-dimension array’s length:

Public Function GetArrLength(a As Variant) As Long
   If IsEmpty(a) Then
      GetArrLength = 0
   Else
      GetArrLength = UBound(a) - LBound(a) + 1
   End If
End Function

Need to calculate the size of a 2D array? Check out our tutorial: Calculate Size of Array.

Loop Through Array

There are two ways to loop through an array.  The first loops through the integers corresponding to the number positions of the array. If you know the array size you can specify it directly:

Sub ArrayExample_Loop1()
    Dim strNames(1 To 4) As String
    Dim i As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For i = 1 To 4
        MsgBox strNames(i)
    Next i
End Sub

However, if you don’t know the array size (if the array is dynamic), you can use the LBound and UBound functions from the previous section:

Sub ArrayExample_Loop2()
    Dim strNames(1 To 4) As String
    Dim i As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For i = LBound(strNames) To UBound(strNames)
        MsgBox strNames(i)
    Next i
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

For Each Array Loop

The second method is with a For Each Loop. This loops through each item in the array:

Sub ArrayExample_Loop3()
    Dim strNames(1 To 4) As String
    Dim Item

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For Each Item In strNames
        MsgBox Item
    Next Item
End Sub

The For Each Array Loop will work with multi-dimensional arrays in addition to one-dimensional arrays.

Loop Through 2D Array

You can also use the UBound and LBound functions to loop through a multi-dimensional array as well. In this example we will loop through a 2D array.  Notice that the UBound and LBound Functions allow you to specify which dimension of the array to find the upper and lower bounds (1 for first dimension, 2 for second dimension).

Sub ArrayExample_Loop4()
    Dim strNames(1 To 4, 1 To 2) As String
    Dim i As Long, j As Long

    strNames(1, 1) = "Shelly"
    strNames(2, 1) = "Steve"
    strNames(3, 1) = "Neema"
    strNames(4, 1) = "Jose"
    
    strNames(1, 2) = "Shelby"
    strNames(2, 2) = "Steven"
    strNames(3, 2) = "Nemo"
    strNames(4, 2) = "Jesse"
    
    For j = LBound(strNames, 2) To UBound(strNames, 2)
        For i = LBound(strNames, 1) To UBound(strNames, 1)
            MsgBox strNames(i, j)
        Next i
    Next j
End Sub

Other Array Tasks

Clear Array

To clear an entire array, use the Erase Statement:

Erase strNames

Usage Example:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"

    Erase strNames
End Sub

Alternatively, you can also ReDim the array to resize it, clearing part of the array:

ReDim strNames(1 to 2)

This resizes the array to size 2, deleting positions 3 and 4.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Count Array

You can count the number of positions in each dimension of  an array using the UBound and LBound Functions (discussed above).

You can also count the number of entered items (or items that meet certain criteria) by looping through the array.

This example will loop through an array of objects, and count the number of non-blank strings found in the array:

Sub ArrayLoopandCount()
    Dim strNames(1 To 4) As String
    Dim i As Long, n As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    
    For i = LBound(strNames) To UBound(strNames)
        If strNames(i) <> "" Then
            n = n + 1
        End If
    Next i
    
    MsgBox n & " non-blank values found."
End Sub

Remove Duplicates

At some point, you may want to remove duplicates from an Array. Unfortunately, VBA does not have a built-in feature to do this. However, we’ve written a function to remove duplicates from an Array (it’s too long to include in this tutorial, but visit the link to learn more).

Filter

The VBA Filter Function allows you to Filter an Array. It does so by creating a new array with only the filtered values.  Below is a quick example, but make sure to read the article for more examples for different needs.

Sub Filter_Match()
 
    'Define Array
    Dim strNames As Variant
    strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")
 
    'Filter Array
    Dim strSubNames As Variant
    strSubNames = Filter(strNames, "Smith")
    
    'Count Filtered Array
    MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."
 
End Sub

IsArray Function

You can test if a variable is an array using the IsArray Function:

Sub IsArrayEx()

    'Creates array with positions 1,2,3
    Dim arrDemo1(3) As String
    
    'Creates regular string variable
    Dim str As String
    
    MsgBox IsArray(arrDemo1)
    MsgBox IsArray(str)

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Join Array

You can quickly “join” an entire array together with the Join Function:

Sub Array_Join()
    Dim strNames(1 To 4) As String
    Dim joinNames As String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    joinNames = Join(strNames, ", ")
    MsgBox joinNames
End Sub

Split String into Array

The VBA Split Function will split a string of text into an array containing values from the original string. Let’s look at an example:

Sub Array_Split()
    Dim Names() As String
    Dim joinedNames As String
    
    joinedNames = "Shelly,Steve,Nema,Jose"
    Names = Split(joinedNames, ",")

    MsgBox Names(1)
End Sub

Here we split this string of text “Shelly,Steve,Nema,Jose” into an array (size 4) using the a comma delimiter (,”).

Const Array

An Array cannot be declared as a constant in VBA. However, you can work around this by creating a function to use as an Array:

' Define ConstantArray
Function ConstantArray()
    ConstantArray = Array(4, 12, 21, 100, 5)
End Function

' Retrive ConstantArray Value
Sub RetrieveValues()
    MsgBox ConstantArray(3)
End Sub

Copy Array

There is no built-in way to copy an Array using VBA. Instead you will need to use a loop to assign the values from one array to another.

Sub CopyArray()

    Dim Arr1(1 To 100) As Long
    Dim Arr2(1 To 100) As Long
    Dim i As Long
    
    'Create Array1
    For i = 1 To 100
        Arr1(i) = i
    Next i
    
    'CopyArray1 to Array2
    For i = 1 To 100
        Arr2(i) = Arr1(i)
    Next i
    
    MsgBox Arr2(74)

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Transpose

There is no built-in VBA function to allow you to Transpose an array. However, we’ve written a function to Transpose a 2D Array. Read the article to learn more.

Function Return Array

A common question VBA developers have is how to create a function that returns an array. I think most of the difficulties are resolved by using Variant Arrays. We’ve written an article on the topic: VBA Function Return Array.

Using Arrays in Access VBA

Most of the Array examples above work exactly the same in Access VBA as they do in Excel VBA.   The one major difference is that when you wish to populate an array using Access data, you would need to loop through the RecordSet object rather than the Range object.

Sub RangeToArrayAccess()
   On Error Resume Next
   Dim strNames() As String
   Dim i As Long
   Dim iCount As Long
   Dim dbs As Database
   Dim rst As Recordset
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
   With rst
      .MoveLast
      .MoveFirst
      iCount = .RecordCount
      ReDim strNames(1 To iCount)
      For i = 1 To iCount
         strNames(i) = rst.Fields("ClientName")
         .MoveNext
      Next i
   End With
   rst.Close
   Set rst = Nothing
   Set dbs = Nothing
End Sub

VBA Arrays in Excel

Excel VBA Arrays

In VBA, an array is a memory location which is capable of storing some value or more than one value in it. There are 3 types of arrays in VBA, One Dimension, Two Dimensions and Multi Dimensions.  One dimension uses one index, such single category of age group, Two Dimension uses 2 indexes such as people and their ages, and Multi Dimension array has more than 2 indexes such as surface height at different levels. We can declare Static and Dynamic variables in Excel for Array.

How to Use Excel VBA Arrays?

Let’s understand how to use Excel VBA Arrays and their types with some examples.

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

Example #1

Take a look at the below example. X is a variable which holds the data type of integer.

Code:

Sub Array_Example1()
Dim x As Integer

x = 1

End Sub

Now assign a value of 1 to the declared variable x.

VBA Arrays Example 1-1

Let’s insert the value of 1 to the cell A1.

Code:

Sub Array_Example1()
Dim x As Integer

x = 1

Range("A1").Value = x
End Sub

Example 1-2

The x value is equal to 1, and in the range, A1 the value will be inserted as the value of x, i.e. the value of x is 1. Now run the code using the F5 key or manually to see results.

Example 1-3

In the above example, x holds only one variable; that’s all. But if I want to insert 5 consecutive numbers by using the single variable, I need to use the type array variable, which can hold many variable values in a single variable name.

Example #2

Now take a look at the below example. A variable name is x, and the data type is LONG. But while declaring the variable itself, I have opened the bracket and mentioned 1 to 5. This means variable x will hold 5 different types of values.

Code:

Sub Array_Example()

Dim x(1 To 5) As Long, i As Integer

End Sub

Example 2-1

After that, I have assigned the values to each variable. X(1) = 20 means the first variable should be equal to the value of 20. X(2) = 25 means the second variable should be equal to the value of 25 and so on.

Code:

Sub Array_Example()

    Dim x(1 To 5) As Long, i As Integer

    x(1) = 20
    x(2) = 25
    x(3) = 44
    x(4) = 78
    x(5) = 96

End Sub

Example 2-2

Later I have declared one more variable called “I” this is the second type of a variable and holds the data type of integer.

In the next step, I have applied FOR loops to insert assigned numbers to the array in the first column. I have set the value of the variable to 1, and I have instructed the loop to run for 1 to 5 times. When the loop is running for the first time i value will be equal to 1. CELLS (I,1).value = x(i) this means for the first time i is equal to 1 i.e. CELLS(1,1).value = x(1), in the first row first column (Cell A1) the value will be the first array (x(1)) value i.e. 20.

When the loop runs for the second time i value becomes 2 i.e. CELLS (2, 1).value = x (2), in the second row first column (A2) the value will be the second array ( x(2) ) value i.e. 25.

Code:

Sub Array_Example()

Dim x(1 To 5) As Long, i As Integer

x(1) = 20
x(2) = 25
x(3) = 44
x(4) = 78
x(5) = 96

For i = 1 To 5

Cells(i, 1).Value = x(i)

Next i

End Sub

Example 2-3

Like this, when the loops keep running, the values will keep changing. When the loops run for the third time A3 cell value will be 44, the fourth-time loop runs A4 cell value will be 78 when the loops run for the final time or fifth time A5 cell value will be 96.

After running the code using the F5 key or manually, we will get results as shown below.

Example 2-4

Types of Arrays in Excel

Arrays have different types in VBA. There are five types of arrays available in excel.

  • Static Array
  • Dynamic Array
  • One Dimensional Array
  • Two Dimensional Array
  • Multi-Dimensional Array

Static Array

In this type of array, the length of the array is pre-determined in advance and remains constant.

Code:

Sub Static_Example()

Dim ArrayType(1 To 3) As Integer

ArrayType(1) = 0
ArrayType(2) = 1
ArrayType(3) = 2

Cells(1, 1).Value = ArrayType(1)
Cells(1, 2).Value = ArrayType(2)
Cells(1, 3).Value = ArrayType(3)

End Sub

Static Arrays Example 1-1

In the above code, ArrayType length is determined well in advance as 1 to 3, and the data type is Integer.

After running the code using the F5 key or manually, we will get results as shown below.

  Static Arrays Example 1-2

Dynamic Array

In this type of array, the length of the array is not pre-determined well in advance.

Code:

Sub Dynamic_Example()

Dim ArrayType() As Variant

ReDim ArrayType(3)

ArrayType(1) = "My Name"
ArrayType(2) = "is"
ArrayType(3) = "Excel"

Cells(1, 1).Value = ArrayType(1)
Cells(1, 2).Value = ArrayType(2)
Cells(1, 3).Value = ArrayType(3)

End Sub

Dynamic Arrays Example 1

In this type of array, data is Variant, and the length is not determined here. After declaring the variable, I have assigned the length of the array by using the ReDim function. This array will insert the values like this Cell A1 = My Name, Cell B1 = is Cell C1 = Excel.

Dynamic Arrays Example 1-2

One Dimensional Array

In this type of array, the length is determined, but in one dimension, it works.

Code:

Sub One_Dimensional()

Dim OneDimension(1 To 3) As String

OneDimension(1) = 40
OneDimension(2) = 50
OneDimension(3) = 15

End Sub

One Dimensional Array 1

Show these value in VBA Message Box.

Code:

Sub One_Dimensional()

Dim OneDimension(1 To 3) As String

OneDimension(1) = 40
OneDimension(2) = 50
OneDimension(3) = 15

MsgBox OneDimension(1) & "," & OneDimension(2) & "," & OneDimension(3)

End Sub

One Dimensional Array 2

Run this code using the F5 key or manually, and we will get the following result.

One Dimensional Array 3

Two Dimensional Array

In this type of array, the length is determined in two dimensions, and it works.

Code:

Sub Two_Dimensional()

Dim TwoDimension(1 To 2, 1 To 2) As Long
Dim i As Integer
Dim j As Integer

TwoDimension(1, 2) = 40
TwoDimension(2, 1) = 50
TwoDimension(1, 1) = 15
TwoDimension(2, 2) = 10

End Sub

Two Dimensional Array 1

Now to store these values to the cells below code.

Code:

Sub Two_Dimensional()

Dim TwoDimension(1 To 2, 1 To 2) As Long
Dim i As Integer
Dim j As Integer

TwoDimension(1, 2) = 40
TwoDimension(2, 1) = 50
TwoDimension(1, 1) = 15
TwoDimension(2, 2) = 10

For i = 1 To 2
    For j = 1 To 2
        Cells(i, j) = TwoDimension(i, j)
    Next  j
Next  i

End Sub

Two Dimensional Array 2

This will store the data like below.

Two Dimensional Array 3

Multi-Dimensional Array

In this type of array, the length is determined, but in multi-dimension, it works.

Code:

Sub Multi_Dimensional()

Dim TwoDimension(1 To 3, 1 To 2) As Long
Dim i As Integer
Dim j As Integer

MultiDimension(1, 1) = 15
MultiDimension(1, 2) = 40
MultiDimension(2, 1) = 50
MultiDimension(2, 2) = 10
MultiDimension(3, 1) = 98
MultiDimension(3, 2) = 54

Multi Dimensional Array 1

If you look at the above code, firstly, I have declared the array as 1 to 3 and then 1 to 2. This means when I am writing the array, firstly, I can use only 1 to 3 numbers, but in the second space, I can use only 1 to 2, not 1 to 3.

Using Loop, we can insert values in cells. I have used two loops for a multi-dimensional array.

Code:

Sub Multi_Dimensional()

Dim TwoDimension(1 To 3, 1 To 2) As Long
Dim i As Integer
Dim j As Integer

MultiDimension(1, 1) = 15
MultiDimension(1, 2) = 40
MultiDimension(2, 1) = 50
MultiDimension(2, 2) = 10
MultiDimension(3, 1) = 98
MultiDimension(3, 2) = 54

For i = 1 To 3
    For j = 1 To 2
        Cells (i, j) = MultiDimension (i,  j)
    Next j
Next i

End Sub

Multi Dimensional Array 2

After running the code using the F5 key or manually, we will get results as shown below.

Multi Dimensional Array 3

Things to Remember

  • An array will count the values from zero, not from 1.
  • Array (0, 0) means first-row first column.
  • This excel macro file needs to be saved as a macro-enabled workbook.
  • In the case of a Dynamic array, we need to assign the value of the array by using the REDIM function in VBA.

Recommended Articles

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

  1. VBA Function
  2. VBA Range Object
  3. VBA VLOOKUP
  4. VBA Web Scraping

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
  1. In the first part of the code, you have variables that you need to use in the code further.
  2. After that, the next part is to generate random numbers by using RND to get you 10 values for the array.
  3. Next, an input box to let enter the value that you want to search within the array.
  4. 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.
  5. 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.
  6. The last part of the code shows you a message about whether a value is found or not.

Понравилась статья? Поделить с друзьями:
  • Using are and is in a sentence for each word
  • Using approve it in word
  • Using appendices in word
  • Using another word instead
  • Using and twice in a sentence for each word