VBA Arrays

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

Description
VBA Code
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
Erase
Erase arr
Array to String
Dim sName As String
sName = Join(arr, “:”)
Increase Size
ReDim Preserve arr(0 To 100)
Set Value
arr(1) = 22

VBA Array Quick Examples

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

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:

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:

Or you can enter only the array size:

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:

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

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.

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)

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:

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

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

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:

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.

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:

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

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

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:

Assign Range to Array

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

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:

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

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.

2D Array Example

This procedure contains an example of a 2D array:

3D Array Example

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

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:

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

Array Length Function

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

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:

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:

For Each Array Loop

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

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

Other Array Tasks

Clear Array

To clear an entire array, use the Erase Statement:

Usage Example:

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

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

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:

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.

IsArray Function

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

Join Array

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

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:

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:

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.

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.

 

Array Tutorials 
Array Mega-Guideyes
Get Array Size
Clear Array
Filter Array
Transpose Array
Function Return Array
Remove Duplicates

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)