VBA Arrays
Written by
Reviewed by
In this Article
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
arr(1) = “one”
arr(2) = “two”
arr(3) = “three”
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
For i = LBound(arr) To UBound(arr)
MsgBox arr(i)
Next i
sName = Join(arr, “:”)
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.
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.
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"
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).
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
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
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.
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
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
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
Array Tutorials | |
---|---|
Array Mega-Guide | yes |
Get Array Size | |
Clear Array | |
Filter Array | |
Transpose Array | |
Function Return Array | |
Remove Duplicates | |