Arrays in excel vba from a range

Using the shape of the Range

Another approach in creating a function for ArrayFromRange would be using the shape and size of the Range to determine how we should structure the array. This way we don’t have to load the data into an intermediate array to determine the dimension.

For instance, if the target range is only one cell, then we know we want to return an array with the single value in it Array(target.value).

Below is the complete function that should deal with all cases. Note, this uses the same technique of using the Application.Transpose method to reshape the array.

' Helper function that returns an array from a range with the
' correct dimensions. This fixes the issue of single values
' not returning as an array, and when a 2 dimension array is returned
' when it only has 1 dimension of data.
'
' @author Robert Todar <robert@roberttodar.com>
Public Function ArrayFromRange(ByVal target As Range) As Variant
    Select Case True
        ' Single cell
        Case target.Cells.Count = 1
            ArrayFromRange = Array(target.Value)
            
        ' Single Row
        Case target.Rows.Count = 1
            ArrayFromRange = Application.Transpose( _
                Application.Transpose(target.Value) _
            )
        
        ' Single Column
        Case target.Columns.Count = 1
            ArrayFromRange = Application.Transpose(target.Value)
            
        ' Multi dimension array
        Case Else
            ArrayFromRange = target.Value
    End Select
End Function

Testing the ArrayFromRange function

As a bonus, here are the tests that I ran to check that this function works.

' @requires {function} ArrayDimensionLength
' @requires {function} ArrayCount
Private Sub testArrayFromRange()
    ' Setup a new workbook/worksheet for
    ' adding testing data
    Dim testWorkbook As Workbook
    Set testWorkbook = Workbooks.Add
    Dim ws As Worksheet
    Set ws = testWorkbook.Worksheets(1)
    
    ' Add sample data for testing.
    ws.Range("A1:A2") = Application.Transpose(Array("A1", "A2"))
    ws.Range("B1:B2") = Application.Transpose(Array("B1", "B2"))
    
    ' This section will run all the tests.
    Dim x As Variant
    
    ' Single cell
    x = ArrayFromRange(ws.Range("A1"))
    Debug.Assert ArrayDimensionLength(x) = 1
    Debug.Assert ArrayCount(x) = 1
    
    ' Single Row
    x = ArrayFromRange(ws.Range("A1:B1"))
    Debug.Assert ArrayDimensionLength(x) = 1
    Debug.Assert ArrayCount(x) = 2
    
    ' Single Column
    x = ArrayFromRange(ws.Range("A1:A2"))
    Debug.Assert ArrayDimensionLength(x) = 1
    Debug.Assert ArrayCount(x) = 2
    
    ' Multi Column
    x = ArrayFromRange(ws.Range("A1:B2"))
    Debug.Assert ArrayDimensionLength(x) = 2
    Debug.Assert ArrayCount(x) = 4
    
    ' Cleanup testing environment
    testWorkbook.Close False
    
    ' Print result
    Debug.Print "testArrayFromRange: PASS"
End Sub

Helper functions for the tests

In my tests I used two helper functions: ArrayCount, and ArrayDimensionLength. These are listed below for reference.

' Returns the length of the dimension of an array
'
' @author Robert Todar <robert@roberttodar.com>
Public Function ArrayDimensionLength(sourceArray As Variant) As Integer
On Error GoTo catch
    Do
        Dim currentDimension As Long
        currentDimension = currentDimension + 1
        
        ' `test` is used to see when the
        ' Ubound throws an error. It is unused
        ' on purpose.
        Dim test As Long
        test = UBound(sourceArray, currentDimension)
    Loop
catch:
    ' Need to subtract one because the last
    ' one errored out.
    ArrayDimensionLength = currentDimension - 1
End Function
' Get count of elements in an array regardless of
' the option base. This Looks purely at the size
' of the array, not the contents within them such as
' empty elements.
'
' @author Robert Todar <robert@roberttodar.com>
' @requires {function} ArrayDimensionLength
Public Function ArrayCount(ByVal sourceArray As Variant) As Long
    Dim dimensions As Long
    dimensions = ArrayDimensionLength(sourceArray)
    
    Select Case dimensions
        Case 0
            ArrayCount = 0
        
        Case 1
            ArrayCount = (UBound(sourceArray, 1) - LBound(sourceArray, 1)) + 1
        
        Case Else
            ' Need to set arrayCount to 1 otherwise the
            ' loop will keep multiplying by zero for each
            ' iteration
            ArrayCount = 1
           
            Dim dimension As Long
            For dimension = 1 To dimensions
                ArrayCount = ArrayCount * _
                    ((UBound(sourceArray, dimension) - LBound(sourceArray, dimension)) + 1)
            Next
    End Select
End Function

ThreeWave
VBA Arrays And Worksheet Ranges

This page describes how to transfer data between VBA arrays and worksheet ranges.
ShortFadeBar

Data transfer between worksheet cells and VBA variables is an expensive operation
that should be kept to a minimum. You can considerably increase the performance of your Excel application
by passing arrays of data to the worksheet, and vice versa, in a single operation rather
than one cell at a time. If you need to do extensive calculations on data in VBA,
you should transfer all the values from the worksheet to an array, do the calculations
on the array, and then, possibly, write the array back to the worksheet. This keeps the number
of times data is transferred between the worksheet and VBA to a minimum. It is far more
efficient to transfer one array of 100 values to the worksheet than to transfer 100 items at a time.

This page shows you how to transfer data between worksheet cells and VBA ararys.
You will find that with large amounts of data being transferred between the
worksheet and the array, working with the array is much faster than working
directly with worksheet cells.

It is very simple to read a range on a worksheet and put it into an array
in VBA. For example,

Dim Arr() As Variant 
Arr = Range("A1:C5")

When you bring in data from a worksheet to a VBA array, the array is always
2 dimensional. The first dimension is the rows and the second dimension is
the columns. So, in the example above, Arr is implicitly sized as
Arr(1 To 5, 1 To 3) where 5 is the number of rows and
3 is the number of columns. A 2 dimensional array is created even if the worksheet data
is in a single row or a single column (e.g, Arr(1 To 10, 1 To 1)).
The array into which the worksheet data is loaded always has an lower bound
(LBound) equal to 1, regardless of what Option Base
directive you may have in your module. You cannot change this behavior. For example,

Dim Arr() As Variant
Arr = Range("A1:A10")

Here, Arr is dimensioned automatically by VBA as Arr(1 to 10,
1 To 1)
.

You can use code like the following to loop through the array of the worksheet values:

Dim Arr() As Variant
Arr = Range("A1:B10")
Dim R As Long
Dim C As Long
For R = 1 To UBound(Arr, 1) 
    For C = 1 To UBound(Arr, 2) 
        Debug.Print Arr(R, C)
    Next C
Next R

There is a special case when the range on the worksheet is a single cell. Expanding on the code above,
you should use the code below if it is possible that the range is a single cell:

Dim Arr() As Variant
Dim RangeName As String
Dim R As Long
Dim C As Long
Dim RR As Range

RangeName = "TheRange"
Set RR = Range(RangeName)
If RR.Cells.Count = 1 Then
    ReDim Arr(1 To 1, 1 To 1)
    Arr(1, 1) = RR.Value
Else
    Arr = Range(RangeName)
End If

Once you have calculated an array with the appropriate values, you
can write it back to the worksheet. The array may be 1 or 2 dimensional.

To write a one dimensional array back to the worksheet, you must create a
Range object, resize that range to the size of your
array, and then write to the range.

Suppose we have a one dimensional array and want to write that out to the worksheet starting
at cell K1. The code must first resize the destination range. For
example,

Dim Destination As Range
Set Destination = Range("K1")
Set Destination = Destination.Resize(1, UBound(Arr))
Destination.Value = Arr

This code will write the values of Arr to range that is
one row tall by UBound(Arr) columns wide, starting at
range K1. If you want the results passed to a range that is
one column wide spanning several rows, use code like the following to resize the range
and set the values.

Dim Destination As Range
Set Destination = Range("K1")
Set Destination = Destination.Resize(UBound(Arr), 1)
Destination.Value = Application.Transpose(Arr)

NOTE that the parameters to Resize are reversed and that
the array Arr is transposed before being written to the worksheet.

If you have a 2 dimensional array, you need to use Resize to
resize the destination range to the proper size. The first dimension is the number of rows
and the second dimension is the number of columns. The code below illustrates writing an array
Arr out to the worksheet starting at cell K1.

Dim Destination As Range
Set Destination = Range("K1")
Destination.Resize(UBound(Arr, 1), UBound(Arr, 2)).Value = Arr

You can transpose the array when writing to the worksheet:

Set Destination = Range("K1")
Destination.Resize(UBound(Arr, 2), UBound(Arr, 1)).Value = Application.Transpose(Arr)

Here, the parameters to Resize are reversed and the array
Arr is transposed.

When you read from a worksheet to an array variable, VBA will automatically size
the array to hold the range on the worksheet. You don’t have to concern yourself
with sizing the array. However, when writing an array from VBA to the worksheet,
you must resize the destination range to hold the array. We saw this earlier in
the examples. Basically, you use code like the following.

Dim NumRows As Long
Dim NumCols As Long
NumRows = UBound(Arr,1) - LBound(Arr,1) + 1
NumCols = UBound(Arr,2) - LBound(Arr,2) + 1
Set Destination = Range("K1").Resize(NumRows, NumCols).Value = Arr

If the array being passed to the worksheet is smaller than the Range to which it is written, the
unused cells get a #N/A error. If the array being passed is larger than
the range to which it is written, the array is truncated on the right or bottom to fit the range.

As you’ve seen in the examples, passing array between the worksheet and VBA is really quite simple. Used correctly,
the code snippets above can have a strong effect on increasing the performance of your VBA application.

ShortFadeBar

LastUpdate This page last updated: 13-September-2012.

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

Summary

This article contains sample Microsoft Visual Basic for Applications procedures that you can use to work with several types of arrays.

More Information

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. NOTE: In Visual Basic for Applications procedures, the words after the apostrophe (‘) are comments.
 

To Fill an Array and Then Copy It to a Worksheet

  1. Open a new workbook and insert a Visual Basic module sheet.

  2. Type the following code on the module sheet.

    Sub Sheet_Fill_Array()
       Dim myarray As Variant
       myarray = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
       Range("a1:a10").Value = Application.Transpose(myarray)
    End Sub
    

  3. Select Sheet1.

  4. On the Tools menu, point to Macro and then click Macros.

  5. In the Macro dialog box, click Sheet_Fill_Array, and then click Run.

To Take Values from a Worksheet and Fill the Array

  1. Type values on Sheet1 in cells A1:A10.

  2. On a Visual Basic module sheet, type the following code:

    Sub from_sheet_make_array()
       Dim thisarray As Variant
       thisarray = Range("a1:a10").Value
    
       counter = 1                'looping structure to look at array
       While counter <= UBound(thisarray)
          MsgBox thisarray(counter, 1)
          counter = counter + 1
       Wend
    End Sub
    

  3. Select Sheet1.

  4. On the Tools menu, point to Macro and then click Macros.

  5. In the Macro dialog box, click from_sheet_make_array, and then click Run.

To Pass and Receive an Array

  1. On a module sheet, type the following code:

    Sub pass_array()
       Dim thisarray As Variant
       thisarray = Selection.Value
       receive_array (thisarray)
    End Sub
    
    Sub receive_array(thisarray)
       counter = 1
       While counter <= UBound(thisarray)
          MsgBox thisarray(counter, 1)
          counter = counter + 1
       Wend
    End Sub
    

  2. Select Sheet1, and highlight the range A1:A10.

  3. On the Tools menu, point to Macro and then click Macros.

  4. In the Macro dialog box, click pass_array, and then click Run.

To Compare Two Arrays

  1. Create two named ranges on Sheet1. Name one range1 and the other range2.

    For example, highlight the cell range A1:A10 and name it range1; highlight the cell range B1:B10 and name it range2.

  2. Type the following code on the module sheet.

    Sub compare_two_array()
       Dim thisarray As Variant
       Dim thatarray As Variant
    
       thisarray = Range("range1").Value
       thatarray = Range("range2").Value
       counter = 1
       While counter <= UBound(thisarray)
          x = thisarray(counter, 1)
          y = thatarray(counter, 1)
          If x = y Then
             MsgBox "yes"
          Else MsgBox "no"
          End If
          counter = counter + 1
       Wend
    End Sub
    

  3. Select Sheet2.

  4. On the Tools menu, point to Macro and then click Macro.

  5. In the Macro dialog box, click compare_two_array, and then click Run.

    You will see one message box for every comparison.

To Fill a Dynamic Array

  1. On a module sheet, type the following code:

    Sub fill_array()
    
       Dim thisarray As Variant
       number_of_elements = 3     'number of elements in the array
    
       'must redim below to set size
       ReDim thisarray(1 To number_of_elements) As Integer
       'resizes this size of the array
       counter = 1
       fillmeup = 7
       For counter = 1 To number_of_elements
          thisarray(counter) = fillmeup
       Next counter
    
       counter = 1         'this loop shows what was filled in
       While counter <= UBound(thisarray)
          MsgBox thisarray(counter)
          counter = counter + 1
       Wend
    
    End Sub
    

  2. On the Tools menu, point to Macro and then click Macros.

  3. In the Macro dialog box, click fill_array, and then click Run.

NOTE: Changing the variable «number_of_elements» will determine the size of the array.
 

Need more help?

VBA Read Values from Range to an Array in Excel. We can read values from Range, Cell, or Table to Arrays. Using Range we can read multiple values from one column or from multiple columns or rows. Cell can contain either single value or multiple values. Table also can consists of multiple values in multiple columns or rows. Let us see how to read values from range in different ways in the following tutorial.

Table of Contents:

  • Objective
  • Macro code to Read Values from Range(Single Column) to an Array
  • VBA code to Read Values from Range(Multiple Columns) to an Array
  • Macro code to Read Values from Range(Single Cell) to an Array
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Macro code to Read Values from Range(Single Column) to an Array

Here is the example macro code to Read Values from Range(Single Column) to an Array. In this code we have used range object to define range, UBound is used to set array upper bound and Array is used to store read values from range. It is an example for single dimensional array.

'Read Values from Range(Single Column) to an Array
Sub VBA_Read_Values_from_Range_to_Array_Single_Column()
    
    'Variable Declaration
    Dim aArrayList() As Variant
    Dim iRowNum As Integer, iColNum As Integer
    
    'Assign range to a variable
    aArrayList = Range("B1:B5")
    
    'Loop Through Rows
    For iRowNum = 1 To UBound(aArrayList)
        'Display result in Immediate window
        Debug.Print aArrayList(iRowNum, 1)
    Next iRowNum

End Sub

Output :You can see output on the immediate window. Here is the screenshot of the above macro code output.

Read Values from Single Column to an Array

Read Values from Single Column to an Array

VBA code to Read Values from Range(Multiple Columns) to an Array

Let us see the example macro code to Read Values from Range(Multiple Columns) to an Array. It is an example for Multi dimensional array.

'Read Values from Range(Multiple Columns) to an Array
Sub VBA_Read_Values_from_Range_to_Array_Multiple_Columns()
    
    'Variable Declaration
    Dim aArrayList() As Variant
    Dim iRowNum As Integer, iColNum As Integer
    
    'Assign range to a variable
    aArrayList = Range("A1:D4")
    
    'Loop Through Rows
    For iRowNum = 1 To UBound(aArrayList, 1)
        'Loop Through Columns
        For iColNum = 1 To UBound(aArrayList, 2)
            'Display result in Immediate window
            Debug.Print aArrayList(iRowNum, iColNum)
        Next iColNum
    Next iRowNum

End Sub

Output : You can output on the immediate window. Here is the screenshot of output.

VBA Read Values from Range to an Array

VBA Read Values from Range to an Array

Macro code to Read Values from Range(Single Cell) to an Array

Here is the example macro code to Read Values from Range(Single Cell) to an Array.

'Read Values from Range(Single Cell) to an Array
Sub VBA_Read_Values_from_Range_to_Array_Single_Cell()
    
    'Variable Declaration
    Dim aArrayList() As Variant
    Dim rRange As Range
    Dim iRowNum As Integer, iColNum As Integer
    
    'Define Cell Range
    Set rRange = Range("A1")
    
    'ReDefine Array size
    ReDim aArrayList(1 To 1, 1 To 1)
    
    'Store Cell Range to An Array
    aArrayList(1, 1) = rRange
    
    'Display Message on the Screen
    Debug.Print rRange
    
End Sub

Output : You can output on the immediate window. Here is the screenshot of output.

VBA Read Single Value from Cell to an Array

VBA Read Single Value from Cell to an Array

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Return to VBA Code Examples

In this Article

  • Assign Range to Array
    • Assign Value From a Single Column
    • Assign value from multiple columns

This tutorial will demonstrate how to populate an array with a range of cells.

Assign Range to Array

We can easily populate a Variant array with a range of cells.

Assign Value From a Single Column

This example will loop through Range(“A1:A10”), assigning the the cell values to an array:

Sub TestArrayValuesSingle()
'Declare the array as a variant array
   Dim arRng() As Variant

'Declare the integer to store the number of rows
   Dim iRw As Integer

'Assign range to a the array variable
   arRng = Range("A1:A10")

'loop through the rows - 1 to 10
   For iRw = 1 To UBound(arRng)

'show the result in the immediate window
      Debug.Print arRng(iRw , 1)
   Next iRw 
End Sub

The UBound is used to set the array upper bound (eg 10) so that the loop knows to loop 10 times.

The Debug.Print function will show you the value contained in the array in the immediate window.

Assign value from multiple columns

Sub TestArrayValuesMultiple()
'Declare the array as a variant array
   Dim arRng() As Variant 

'Declare the integer to store the number of rows
   Dim iRw As Integer

'Declare the integer to store the number of columns
   Dim iCol as Integer

'Assign range to a the array variable
   arRng = Range("A1:C10")

'loop through the rows - 1 to 10
   For iRw = 1 To UBound(arRng,1)

'now - while in row 1, loop through the 3 columns
      For iCol = 1 to UBound(arRng,2)

'show the result in the immediate window
         Debug.Print arRng(iRw, iCol)
      Next iCol
   Next iRw 
End Sub

In the code above, we have populated the array with the values in Range(“A1:C10”).

The UBound is once again used – but this time it is needed twice – once to loop through the rows, and then again to loop through the columns.

The Debug.Print function will show you the value contained in the array in the immediate window.

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!
vba save as

Learn More!

Home / VBA / Arrays / VBA Range to an Array

Steps to Add a Range into an Array in VBA

  1. First, you need to declare a dynamic array using the variant data type.
    1-declare-a-dynamic-variable-1
  2. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well.
    2-declare-one-more-variable-2
  3. After that, assign the range where you have value to the array.
    3-assign-the-range-3
  4. From here, we need to create a loop to print all the values to the immediate window so that you can see that all the values are assigned to the array.
    4-create-a-loop-to-print-all-values-4
Sub myArrayRange()

Dim iAmount() As Variant
Dim iNum As Integer

iAmount = Range("A1:A11")

For iNum = 1 To UBound(iAmount)
    Debug.Print iAmount(iNum, 1)
Next iNum

End Sub

And when you run the above code it shows you all the values you have assigned from the range (“A1:A11) to the array iAmount and prints it to the immediate window.

In the same way, you can also use a multi-dimensional array.

Sub myArrayRange()

Dim iAmount() As Variant
Dim iNum1 As Integer

iAmount = Range("A1:B13")

For iNum1 = 1 To UBound(iAmount, 1)
        Debug.Print iAmount(iNum1, 1) & " " & iAmount(iNum1, 2)
Next iNum1

End Sub

Or you can also do this way as well.

Sub myArrayRange()

Dim iAmount() As Variant
Dim iNum1 As Integer
Dim iNum2 As Integer

iAmount = Range("A1:B13")

For iNum1 = 1 To UBound(iAmount, 1)
    For iNum2 = 1 To UBound(iAmount, 2)
        Debug.Print iAmount(iNum1, iNum2)
    Next iNum2
Next iNum1

End Sub

Populating arrays (adding values)

There are multiple ways to populate an array.


Directly

'one-dimensional
Dim arrayDirect1D(2) As String
arrayDirect(0) = "A"
arrayDirect(1) = "B"
arrayDirect(2) = "C"

'multi-dimensional (in this case 3D)
Dim arrayDirectMulti(1, 1, 2)
arrayDirectMulti(0, 0, 0) = "A"
arrayDirectMulti(0, 0, 1) = "B"
arrayDirectMulti(0, 0, 2) = "C"
arrayDirectMulti(0, 1, 0) = "D"
'...


Using Array() function

'one-dimensional only
Dim array1D As Variant 'has to be type variant
array1D = Array(1, 2, "A")
'-> array1D(0) = 1, array1D(1) = 2, array1D(2) = "A"

From range

Dim arrayRange As Variant 'has to be type variant
    
'putting ranges in an array always creates a 2D array (even if only 1 row or column)
'starting at 1 and not 0, first dimension is the row and the second the column
arrayRange = Range("A1:C10").Value
'-> arrayRange(1,1) = value in A1
'-> arrayRange(1,2) = value in B1
'-> arrayRange(5,3) = value in C5
'...
    
'Yoo can get an one-dimensional array from a range (row or column)
'by using the worksheet functions index and transpose:

'one row from range into 1D-Array:
arrayRange = Application.WorksheetFunction.Index(Range("A1:C10").Value, 3, 0)
'-> row 3 of range into 1D-Array
'-> arrayRange(1) = value in A3, arrayRange(2) = value in B3, arrayRange(3) = value in C3

'one column into 1D-Array:
'limited to 65536 rows in the column, reason: limit of .Transpose
arrayRange = Application.WorksheetFunction.Index( _
Application.WorksheetFunction.Transpose(Range("A1:C10").Value), 2, 0)
'-> column 2 of range into 1D-Array
'-> arrayRange(1) = value in B1, arrayRange(2) = value in B2, arrayRange(3) = value in B3
'...

'By using Evaluate() - shorthand [] - you can transfer the
'range to an array and change the values at the same time.
'This is equivalent to an array formula in the sheet:
arrayRange = [(A1:C10*3)]
arrayRange = [(A1:C10&"_test")]
arrayRange = [(A1:B10*C1:C10)]
'...

2D with Evaluate()

Dim array2D As Variant
'[] ist a shorthand for evaluate()
'Arrays defined with evaluate start at 1 not 0
array2D = [{"1A","1B","1C";"2A","2B","3B"}]
'-> array2D(1,1) = "1A", array2D(1,2) = "1B", array2D(2,1) = "2A" ...

'if you want to use a string to fill the 2D-Array:
Dim strValues As String
strValues = "{""1A"",""1B"",""1C"";""2A"",""2B"",""2C""}"
array2D = Evaluate(strValues)

Using Split() function

Dim arraySplit As Variant 'has to be type variant
arraySplit = Split("a,b,c", ",")
'-> arraySplit(0) = "a", arraySplit(1) = "b", arraySplit(2) = "c"

Dynamic Arrays (Array Resizing and Dynamic Handling)

Due to not being Excel-VBA exclusive contents this Example has been moved to VBA documentation.

Link:
Dynamic Arrays (Array Resizing and Dynamic Handling)

Jagged Arrays (Arrays of Arrays)

Due to not being Excel-VBA exclusive contents this Example has been moved to VBA documentation.

Link:
Jagged Arrays (Arrays of Arrays)

Check if Array is Initialized (If it contains elements or not).

A common problem might be trying to iterate over Array which has no values in it. For example:

Dim myArray() As Integer
For i = 0 To UBound(myArray) 'Will result in a "Subscript Out of Range" error

To avoid this issue, and to check if an Array contains elements, use this oneliner:

If Not Not myArray Then MsgBox UBound(myArray) Else MsgBox "myArray not initialised"

Dynamic Arrays [Array Declaration, Resizing]

Sub Array_clarity()

Dim arr() As Variant  'creates an empty array
Dim x As Long
Dim y As Long

x = Range("A1", Range("A1").End(xlDown)).Cells.Count
y = Range("A1", Range("A1").End(xlToRight)).Cells.Count

ReDim arr(0 To x, 0 To y) 'fixing the size of the array

For x = LBound(arr, 1) To UBound(arr, 1)
    For y = LBound(arr, 2) To UBound(arr, 2)
        arr(x, y) = Range("A1").Offset(x, y) 'storing the value of Range("A1:E10") from activesheet in x and y variables
    Next
Next

'Put it on the same sheet according to the declaration:
Range("A14").Resize(UBound(arr, 1), UBound(arr, 2)).Value = arr

End Sub

VBA Range to 2D Array

These list of topics are covered in this page.

  1. Vba Code to initialize 2D Array with Range
  2. Vba to write Array data to worksheet
  3. Resize Array to fit worksheet.

This code converts worksheet data in specific range into an vba array. Lets see how it works.

1.Excel Macro – Convert Range To Array(2-Dimention)

Actually, it does not require any special function. It is almost easy like assigning a value to a variable.

Once you assign the range to the array, Excel automatically calculates & allocates array dimensions. You don’t have to specify the number of rows, columns or dimensions for the array.

Excel decides these parameters automatically & created a 2D Array by default. It will be clear from below example.

'--------------------------------------------------------------------------------
'Visit https://officetricks.com to get more Free & Fully Functional VBA Codes
'--------------------------------------------------------------------------------
Sub Range_To_Array()
    'Declare Array as variant & Range
    Dim rArray() As Variant, rRange As Range, iRow As Double, iCol As Double
    
    'Initialize Range to Reference a portion of Worksheet
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("A1:D2")
    
    'Assign Range to Array
    rArray = rRange.Value
    
    'Read content of Array one by one
    For iRow = 1 To UBound(rArray, 1)
        For iCol = 1 To UBound(rArray, 2)
            Debug.Print rArray(iRow, iCol)
        Next
    Next           
End Sub

Once you convert the worksheet data to array, you get the advantage of using the Array function on the values. This way the code runs much faster than accessing worksheet data each time.

2. Convert Array to Range – Write to Worksheet

When we write values back to worksheet from array, you have to explicitly mention number of rows & columns the data should occupy.

For this first assign a cell to a range variable: set rng = Thisworkbook.Sheet(1).Range(“A1”) & then use range.resize as explained in this code.

Sub ArrayToRange()
    'Declare Array as variant & Range
    Dim rArray() As Variant, rRange As Range, iRow As Double, iCol As Double
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("A1:D2")
    rArray = rRange.Value
    
           
    'Write values in Array back To a Range in worksheet
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("F1:I2")
    rRange = rArray
    
    'OR Resize Range as per the structure of Array
    iRow = UBound(rArray, 1)
    iCol = UBound(rArray, 2)
    Set rRange = ThisWorkbook.Sheets("sheet1").Range("F1")
    Set rRange = rRange.Resize(iRow, iCol)
    MsgBox rRange.Address(0, 0)
    rRange = rArray
End Sub

To know how Range.resize works, read further in the next section.

3. Excel VBA – Resize Array to fit Worksheet

Once it is initialized, then it can be extended or resized as per the structure of the array.

'Get Number of Rows in Array
rows = UBound(arr,1)

'Get number of columns in Array
cols = UBound(arr,2)

'Resize array as per the array dimensions
set rng = rng.resize(rows,cols)

'Write Array value to the Range
rng = arr

So, the Excel VBA function Range.Resize holds the key here. It can be used to expand or compress the target destination range size.

I have often read that processing values from an array is much faster than processing values from Excel sheet. Though, I haven’t tested this. But, in case you want to move the values from worksheet or Table to an Array, then this code can be used.

External Reference: Here is another wonderful article from cpearson about arrays & worksheets.

Like this post? Please share to your friends:
  • Arrayformula excel на русском
  • Array vba excel примеры
  • Array vba excel описание
  • Array to excel phpexcel
  • Array of arrays in excel vba