Excel vba array length

Home / VBA / Arrays / VBA Array Length (Size)

In VBA, to get the length of an array means to count the number of elements you have in that array. For this, you need to know the lowest element and the highest element. So, to get this you can use the UBOUND and LBOUND functions that return the upper bound and lower bound, respectively.

Apart from that, you can also use the COUNTA which is a worksheet function. And in this tutorial, we will see both of the methods so you can use any of them at your convenience.

Steps to Get the Size of an Array

Here we have an array that contains a list of months and sales quantity for each month.

  1. Make sure to have an array declared properly with rows and columns.
    2-array-declared-properly-2
  2. After that, two more variables (as we have a two-dimensional array) to store the bounds of the array.
    3-store-the-bounds-of-an-array-3
  3. Next, you need to use a formula where you have to use the Ubound function to get the upper bound and then Lbound to get the lower bound of the array.
  4. As you have a two-dimensional array you need to get bound for both of the dimensions and set that value to the variables.
    4-use-the-ubound-function-4
  5. In the end, multiply lengths that you have got from the Ubound and Lbound as upper and lower bound.
    5-ubound-and-lbound-as-lower-and-upper-5

Here’s the full code.

Dim yearSales(1 To 12, 1 To 2) As Integer
Dim iCount1 As Integer, iCount2 As Integer
   
iCount1 = UBound(yearSales, 1) - LBound(yearSales, 1) + 1
iCount2 = UBound(yearSales, 2) - LBound(yearSales, 2) + 1
   
MsgBox iCount1 * iCount2

Note: You must be wondering that we have a total of 13 rows in the array that I shared with you at the start of the post.

But we have used an array with 13 rows because the first row was a heading. And here we have used an IF STATEMENT and ISEMPTY function to check if the declared array has zero elements.

Dim yearSales(1 To 12, 1 To 2) As Integer
Dim iCount1 As Integer, iCount2 As Integer
If IsEmpty(yearSales) = 0 Then
    MsgBox "This array has zero elements."
Else
    iCount1 = UBound(yearSales, 1) - LBound(yearSales, 1) + 1
    iCount2 = UBound(yearSales, 2) - LBound(yearSales, 2) + 1
    MsgBox "This array has " & iCount1 * iCount2 & " element(s)."

Using COUNTA to get the Length of the Array

As you know that an array is a bunch of elements that are structured in a single or multi-dimensional way and you can use the COUNTA function (worksheet function) to count these elements in one go.

In the following code, you have used the same array that you have declared earlier and then used a variable to store the element count returned by the function.

And as you can see the result it has returned is 24 that’s the count of the total number of elements that we have in the array.

Dim yearSales(1 To 12, 1 To 2) As Integer
iCount = WorksheetFunction.CountA(yearSales)
MsgBox iCount

There’s one thing that you need to take care of that this method won’t be ideal to use in all situations, so it’s always good to use the method that we have discussed earlier.

You can also write a code to check first if the declared array is not blank.

Dim yearSales(1 To 12, 1 To 2) As Integer
If IsEmpty(yearSales) = 0 Then
    MsgBox "This array has zero elements."
Else
    iCount = WorksheetFunction.CountA(yearSales)
    MsgBox "This array has " & iCount & " element(s)."

Return to VBA Code Examples

In this Article

  • Get Array Length
    • LBound and UBound Functions
    • Get Array Length Function
  • Get 2D Array Size

This tutorial will teach you how to get the length (size) of an Array in VBA.

Get Array Length

In order to get the length of an Array, you need to know the array’s start and end positions. You can do this with the VBA’s UBound and LBound Functions.

LBound and UBound Functions

This procedure demonstrates how to use the UBound and LBound Functions on a a single dimension array:

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

Subtracting the two will give you the array length (UBound – LBound +1).

Get Array Length Function

This function will calculate the size (length) of a single-dimensional Array:

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

Get 2D Array Size

This function will calculate the number of positions in a two-dimensional array:

Sub testArrySize()
    Dim arr2D(1 To 4, 1 To 4) As Long
    
    MsgBox GetArrSize_2D(arr2D)

End Sub


Public Function GetArrSize_2D(a As Variant) As Long
   Dim x As Long, y As Long
   
   If IsEmpty(a) Then
      GetArrSize_2D = 0
   Else
      x = UBound(a, 1) - LBound(a, 1) + 1
      y = UBound(a, 2) - LBound(a, 2) + 1
      GetArrSize_2D = x * y
   End If
End Function

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!

We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail.

Syntax: UBound() function

UBound (arrayname, [ dimension ])

Parameters:

  • arrayname: required. Array variable name
  • dimension: optional

Returns: Return upper limit of an array dimension.

Syntax: LBound() Function

LBound (arrayname, [ dimension ])

Parameters:

  • arrayname : required. Array variable name
  • dimension : optional

Returns: Return lower limit of an array dimension

Sample Data: 

VBA Code to get the length of Array (one-dimensional array):

Declare Variables:

Declaring a customer array with the size of 10.

Sub oneDimArrayLength()
' Array variable Declaration
Dim customer (1 To 10) As String

Assign values to array elements

customer(1) = "ANTON"
customer(2) = "BERGS"
customer(3) = "BOLID"
customer(4) = "KOENE"
customer(5) = "FRANS"

Use UBound function to get the size of an array and Message box to display the result

'Message box to popup length of 1D array
MsgBox "Array has " & UBound(customer) & " element(s)."

End Sub

To Run VBA Code

Press Alt+F8 to popup macro window.  Select ” oneDimArrayLength” and Click Run button.

Output

VBA Code to get the length of Array (multi-dimensional array)

Declaring variables:

Declaring ProdAndCustomer multi-dimensional array size of 10 rows and 2 columns

Sub twoDimArrayLength()

' Array variable Declaration
Dim ProdAndCustomer(1 To 10, 1 To 2) As String, noOfRow As Integer, noOfCol As Integer, noOfElements As Integer

Assign values to array elements

ProdAndCustomer(1, 1) = "Alice Mutton"
ProdAndCustomer(2, 1) = "Boston Crab Meat"
ProdAndCustomer(3, 1) = "Camembert Pierrot"
ProdAndCustomer(4, 1) = "Alice Mutton"
ProdAndCustomer(5, 1) = "Ipoh Coffee"

ProdAndCustomer(1, 2) = "ANTON"
ProdAndCustomer(2, 2) = "BERGS"
ProdAndCustomer(3, 2) = "BOLID"
ProdAndCustomer(4, 2) = "BOTTM"
ProdAndCustomer(5, 2) = "FURIB"

Compute Number of Rows, Number of Columns using UBound and LBound function.  Multiply by noOfRow and noOfCol variable to get Number of elements in multi-dimensional array. 

noOfRow = UBound(ProdAndCustomer, 1) - LBound(ProdAndCustomer, 1) + 1
noOfCol = UBound(ProdAndCustomer, 2) - LBound(ProdAndCustomer, 2) + 1
noOfElements = noOfRow * noOfCol

Message box to popup result

'Message box to popup length of 1D array
MsgBox "Array has " & noOfElements & " element(s)."

End Sub

To Run VBA Code

Press Alt+F8 to popup macro window.  Select ” twoDimArrayLength” and Click Run button.

Output:

VBA Array length

Introduction to VBA Array Length

Basically, an array is a set of elements that is in two dimensions. In excel we use arrays in our day to day lives. To calculate the length of an array in excel we either do it manually or use some functions to do so. But how do we get the length of an array in Excel VBA? We use two separate functions to do so. Lbound and Ubound functions are used to get an array length in excel VBA.

So we discussed above that we use Lbound and Ubound functions to get array length. But what are Lbound and Ubound functions. Lbound stands for lower bound and Ubound stands for Upper bound. Array length is also identified by function arr.length.

First, let us see how an array looks like. Look at the screenshot below for the same.

Array Example

Above is an array with four rows and two columns. Now how will we find the length of this array or other sizes we will learn in this topic.

First, ensure we have the developer’s tab enabled so that we can use Excel VBA.

How to Use Excel VBA Array Length?

Now let us try on some examples on how to find array length in excel VBA.

You can download this VBA Array Length Excel Template here – VBA Array Length Excel Template

Example #1 – VBA Array Length

First, imagine we have an array size of four elements in each row and columns i.e. four rows and four columns. So the array size would be 16. Array length is the calculated product of a number of rows and columns. Let us do this in Excel VBA.

Step 1: Enter VB editor by going in the developer’s tab and then clicking on visual basic as follows.

Array length Developer

Step 2: Once we are inside the VB editor let us insert a new module which will open code window for us.

Module

Step 3: Double click on the module we just inserted which will open code window for us. Now we can start writing the code by declaring a Sub Function.

Code:

Sub Sample()

End Sub

VBA Array Length 1.1

Step 4: Now declare an array as an integer as follows.

Code:

Sub Sample()

Dim arr(3, 3) As Integer

End Sub

VBA Array Length 1.2

Step 5: Now use the console. writeline and arr.length function to find the array length as follows.

Code:

Sub Sample()

Dim arr(3, 3) As Integer
MsgBox Application.CountA(arr)

End Sub

Example 1.3

Step 6: When we run the above code we get 16 as output as 16 is the length of the integer.

VBA Length 1.1

Example #2 – VBA Array Length

In the above method, we used arr.length method which is not ideal in many cases. We will use the traditional Lbound an Ubound method to find the array length. I have some data in sheet 1 as follows.

Array length 2

In the above screenshot, we have an array and we want to find the size of this array in VBA. We will follow similar steps from example 1 on how to enter the VB editor as follows.

Step 1: Enter VB editor by going in the developer’s tab and then clicking on visual basic as follows.

VBA Array Developer 2

Step 2: Click on insert tab and add a new module.

Module 2

Step 3: Now we can start writing the code by declaring a sub-function.

Code:

Sub Sample1()

End Sub

VBA Array Length 2.2

Step 4: Now first we need to declare an array for our data above and two another integers as follows.

Code:

Sub Sample1()

Dim Grades(1 To 5, 1 To 2) As String, x As Integer, y As Integer

End Sub

Example 2.3

Step 5: Now as we have a size of the array we give an upper and lower limit to the dimension by the following code.

Code:

Sub Sample1()

Dim Grades(1 To 5, 1 To 2) As String, x As Integer, y As Integer
x = UBound(Grades, 1) - LBound(Grades, 1) + 1
y = UBound(Grades, 2) - LBound(Grades, 2) + 1

End Sub

Example 2.4

Step 6: Now let’s use the Msgbox function to display the size of the array from the data above.

Code:

Sub Sample1()

Dim Grades(1 To 5, 1 To 2) As String, x As Integer, y As Integer
x = UBound(Grades, 1) - LBound(Grades, 1) + 1
y = UBound(Grades, 2) - LBound(Grades, 2) + 1
MsgBox "This array Has " & x * y & " Data"

End Sub

Example 2.5

Step 7: Now run the code from the run button or press F5. When we run the code we see the following result,

VBA Array Example 1

Now we can check from the data it has 5 rows and two columns and each cell has one data so total there are 10 data.

Example #3 – VBA Array Length

Now let us try to find the size of an array in another example. Now we have data in another sheet.

Example 3.1

Now the data has one more rows from the above example 2. Let us try to find out the size of this array. Follow the following steps,

Step 1: Enter VB editor by going in the developer’s tab and then clicking on visual basic as follows,

VBA Array Example 3.1

Step 2: Double click on the module we just inserted which will open code window for us. Now we can start writing the code by declaring a Sub Function.

Code:

Sub Sample2()

End Sub

VBA Array Length 3.2

Step 3: Now similarly declare an array and two different variables as integers.

Code:

Sub Sample2()

Dim Dept(1 To 6, 1 To 2) As String, x As Integer, y As Integer

End Sub

VBA Array Length 3.3

Step 4: Now use Lbound and Ubound function to find the size of an array as follows.

Code:

Sub Sample2()

Dim Dept(1 To 6, 1 To 2) As String, x As Integer, y As Integer
x = UBound(Dept, 1) - LBound(Dept, 1) + 1
y = UBound(Dept, 2) - LBound(Dept, 2) + 1

End Sub

 VBA Array Length 3.4

Step 5: Now use the Msgbox function to display the size of the array.

Code:

Sub Sample2()

Dim Dept(1 To 6, 1 To 2) As String, x As Integer, y As Integer
x = UBound(Dept, 1) - LBound(Dept, 1) + 1
y = UBound(Dept, 2) - LBound(Dept, 2) + 1
MsgBox "This array size is " & x * y

End Sub

VBA Array Length 3.5

Step 6: When we run the code we get the following result,

VBA Array 3

Things to Remember

There are few things which we need to keep in mind for VBA Array length as follows:

  • To find a length of an array we need to declare the array first.
  • We use Lbound and Ubound function to find the length of an array.
  • An array is a set of elements in two dimensions.

Conclusion

  • Now as we discussed earlier what is an array. It is a set of elements in two dimensions. So in excel VBA, we can use Lbound and Ubound function to find the size of the array length.
  • How do we calculate the array size. It is the product of a number of rows to the number of columns.
  • How to use the VBA Array Length Function.
  • In the above examples, we have learned how to use Ubound and Lbound function as follows.
  • UBound(Array, 1) – LBound(Array, 1) + 1

Recommended Articles

This is a guide to VBA Array Length. Here we have discussed how to use Excel VBA Array Length along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA Delete Row
  3. VBA Transpose
  4. VBA LBound

Get array length in VBA

For one dimensional array, you may get the array length (size) by using the UBound function.

Following is the syntax of UBound function:

UBound(arrayname, [ dimension ])

An example to get array size

In the following example, we declared an array and assign values to its elements by index numbers.

Then UBound function is used to get the size that is displayed in the message box:

VBA Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub Arrays_length()

Dim arr_days(7) As String

‘Creating array elements

arr_days(0) = «Sat»

arr_days(1) = «Sun»

arr_days(2) = «Mon»

arr_days(3) = «Tue»

‘Display Array Length

arr_len = UBound(arr_days) + 1

MsgBox «Array has « & arr_len & » elements.»

End Sub

Output:

VBA-array-length

We need to add 1 to the UBound result as the array index starts at 0. So, we have one more item than the returned value of UBound function.

What if array index starts at 2 or more?

If we have an array like this:

Dim arr_days(2 To 7) As String

Then UBound still returns seven, as it’s the upper number in our array. However, the actual number of elements is less.

In that case, you may use UBound with the LBound function – which returns a lower number in the array.

See the simple example below of getting array length:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Sub arr_ex()

Dim arr_days(2 To 7) As String

Dim arrLen As Integer

‘Creating array elements

arr_days(2) = «Sat»

arr_days(3) = «Sun»

arr_days(4) = «Mon»

arr_days(5) = «Tue»

arr_days(6) = «Tue»

arr_days(7) = «Wed»

‘Display Array Length

arrLen = UBound(arr_days) LBound(arr_days) + 1

MsgBox «Array has « & arrLen & » elements.»

End Sub

Output:

array-length-single

Getting array size of a two-dimensional array

There may be different scenarios to get the array size of 2-D array.

Scenario 1:

If your two-dimensional array elements start at 1, for example:

Dim arr_products(1 To 5, 1 To 4) As String

In that case, you may use this simple approach to get number of elements in the 2-D array:

Sub Arrays_ex()

‘Creating a 2D array

Dim arr_products(1 To 6, 1 To 3) As String

Dim i As Integer, j As Integer, k As Integer

‘Using UBound and multiply

i = UBound(arr_products, 1)

j = UBound(arr_products, 2)

k = i * j

MsgBox «2-D Array has « & k & » elements.»

End Sub

Result:

VBA-array-length-2D

What if array index starts beyond 1?

Let us say, your 2-D array is declared like this:

Dim arr_products(3 To 6, 2 To 3) As String

Then our above approach fails, as UBound still returns 6 and 3 and the output remains the same.

In that case, we can use LBound function as well to get the correct array length.

LBound returns the smallest available subscript for the indicated dimension of an array.

See the following solution for our 2D array:

Sub Arrays_ex()

‘Creating a 2D array

Dim arr_products(3 To 6, 2 To 3) As String

Dim i As Integer, j As Integer, k As Integer

‘Using UBound and LBound

i = UBound(arr_products, 1) LBound(arr_products, 1) + 1

j = UBound(arr_products, 2) LBound(arr_products, 2) + 1

k = i * j

MsgBox «2-D Array has « & k & » elements.»

End Sub

Output:

array-length-2D-sce-2

Working with 2-D array length and Excel sheet

Now let’s look at an Excel sheet example to have a better idea of how the above approach worked.

We have the following sample sheet:

array-length-2D-sce-3

We will create a 2-D array from that sheet and get the array length (total cells utilized).

So following is our two-dimensional array:

Dim arr_products(3 To 6, 2 To 3) As String

Assign the cell values as array elements

For x = 1 To 8

For y = 1 To 4

arr_products(x, y) = Cells(x, y).Value

Next y

Next x

Display all array elements in a message box to see what we get from the Excel sheet:

For i = 3 To UBound(arr_products)

Str_Prods = Str_Prods & arr_products(i, 2) & »    « & arr_products(i, 3) & vbNewLine

Next i

‘Display cells/element

MsgBox Str_Prods

Get the 2-D array length:

i = UBound(arr_products, 1) LBound(arr_products, 1) + 1

j = UBound(arr_products, 2) LBound(arr_products, 2) + 1

k = i * j

MsgBox «2-D Array has « & k & » elements.»

Let us combine all of the above code and see the outputs:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

Sub Arrays_ex()

‘Creating a 2D array

Dim arr_products(3 To 6, 2 To 3) As String

Dim x As Integer, y As Integer

Dim i As Integer, j As Integer, k As Integer

‘Assigning cell values as array element values

For x = 3 To 6

For y = 2 To 3

arr_products(x, y) = Cells(x, y).Value

Next y

Next x

‘Displaying whole array in Message Box

For i = 3 To UBound(arr_products)

Str_Prods = Str_Prods & arr_products(i, 2) & »    « & arr_products(i, 3) & vbNewLine

Next i

‘Display cells/element

MsgBox Str_Prods

‘Using UBound and LBound to get array length

i = UBound(arr_products, 1) LBound(arr_products, 1) + 1

j = UBound(arr_products, 2) LBound(arr_products, 2) + 1

k = i * j

‘Display array length

MsgBox «2-D Array has « & k & » elements.»

End Sub

Output:

Message box 1:

array-length-msg1

Message box 2:

array-length-msg2

You can compare the cell data and array length with the sample sheet’s highlighted area above.

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

  1. Get the Difference of the Highest and Lowest Index to Get the Array Length in VBA
  2. Use COUNTA Worksheet Function to Get the Array Length in VBA

Get the Array Length in VBA

Arrays are popular tools in computer programming wherein you can save information needed for later use or during code execution. Almost every computer programming language, arrays are included in their library since the need to save and retrieve information is sometimes inevitable.

In VBA, getting the length of an array means counting the number of an element present inside the array. To do this, you have to know the index’s lowest and highest elements. Then, the difference between the highest from the lowest would be the array length.

Also, you could use the COUNTA worksheet function to get the same information.

This tutorial uses the highest/lowest index difference and the COUNTA worksheet function to get the length on a VBA array.

Get the Difference of the Highest and Lowest Index to Get the Array Length in VBA

The logic of this method is that we can get the array’s length by subtracting the lowest index to the highest index then adding 1. We add 1 since it is needed to include the lowest index in the array’s length.

The code block below will demonstrate getting the array length of an array of a fixed-length array. Note that getting only the highest index to get the array length is not always correct as there are cases where the lowest index is not equal to 0 and could start with different indexes.

Sub ArrayLengthDemo()

Dim stringArr(5 To 9) As String

stringArr(5) = "Glen"
stringArr(6) = "Yumi"
stringArr(7) = "Myla"
stringArr(8) = "Katrina"
stringArr(9) = "Jose"

Debug.Print "The array length of stringArr is " UBound(stringArr) - LBound(stringArr) + 1
End Sub

ArrayLengthDemo Output:

The array length of stringArr is  5

The code block below will demonstrate getting the array length of an array of a dynamic array.

Sub ArrayLengthDemo()

Dim StringArr As Variant

StringArr = Array("Glen", "Yumi", "Katrina", "Myla", "Jose")

Debug.Print "The array length of StringArr is "; UBound(StringArr) - LBound(StringArr) + 1

End Sub

ArrayLengthDemo Output:

The array length of stringArr is  5

Implementing functions to get the array length on the below code will be demonstrated. It will be helpful if the need to get the array length is recurring.

Also, the code below has additional logic to detect if the array to be measured is null.

Public Function GetArrayLength(arr As Variant) As Integer
   If IsEmpty(arr) Then
      GetArrayLength = 0
   Else
      GetArrayLength = UBound(arr) - LBound(arr) + 1
   End If
End Function

Sub GetArrayLengthDemo1()


Dim stringArr(5 To 9) As String

stringArr(5) = "Glen"
stringArr(6) = "Yumi"
stringArr(7) = "Myla"
stringArr(8) = "Katrina"
stringArr(9) = "Jose"

Debug.Print "The array length is " & GetArrayLength(stringArr)

End Sub

Sub GetArrayLengthDemo2()

Dim NullArr As Variant

Debug.Print "The array length is " & GetArrayLength(NullArr)

End Sub

GetArrayLengthDemo1 Output:

GetArrayLengthDemo2 Output:

Use COUNTA Worksheet Function to Get the Array Length in VBA

An array is a collection of elements structured in a single or multi-dimensional fashion. You can use the COUNTA worksheet function to count these elements in a single line of code.

The code block below demonstrates how to get the array length using the COUNTA worksheet function.

Syntax:

WorksheetFunction.CountA([ arrayName ])

Parameter:

[arrayName] the array to be measured

The COUNTA worksheet function is limited only to 30 elements. If dealing with a large array, the first method is suggested.

Sub ArrayLengthDemo()

Dim stringArr(5 To 9) As String

stringArr(5) = "Glen"
stringArr(6) = "Yumi"
stringArr(7) = "Myla"
stringArr(8) = "Katrina"
stringArr(9) = "Jose"

Debug.Print "The array length of stringArr is " & WorksheetFunction.CountA(stringArr)
End Sub

ArrayLengthDemo Output:

The array length of stringArr is 5
Sub ArrayLengthDemo()

Dim StringArr As Variant

StringArr = Array("Glen", "Yumi", "Katrina", "Myla", "Jose")

Debug.Print "The array length of StringArr is " & WorksheetFunction.CountA(stringArr)

End Sub

ArrayLengthDemo Output:

The array length of stringArr is  5 

Понравилась статья? Поделить с друзьями:
  • Excel vba array filter
  • Excel vba array add
  • Excel vba argument not optional что это
  • Excel vba applies to
  • Excel tutorial for beginners