Excel Macro Mastery

Excel VBA Array – The Complete Guide

by Paul Kelly | | Data Structures VBA , Most Popular | 307 comments

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.

  • 1 Related Links for the VBA Array
  • 2 A Quick Guide to the VBA Array
  • 3 Download the Source Code and Data
  • 4 What is the VBA Array and Why do You Need It?
  • 5 Two Types of VBA Arrays
  • 6 VBA Array Initialization
  • 7 Assigning Values to VBA Array
  • 8 VBA Array Length
  • 9 Using the Array and Split function
  • 10.1 Using the For Each Loop with the VBA Array
  • 11 Using Erase with the VBA Array
  • 12.1 Using Preserve with Two-Dimensional Arrays
  • 13 Sorting the VBA Array
  • 14 Passing the VBA Array to a Sub
  • 15 Returning the VBA Array from a Function
  • 16 Using a Two-Dimensional VBA Array
  • 17 Using the For Each Loop
  • 18 Reading from a Range to the VBA Array
  • 19 How To Make Your Macros Run at Super Speed
  • 20 Conclusion
  • 21 What’s Next?

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 Key\Value pair. Very useful in many applications.

The Microsoft guide for VBA Arrays can be found here .

A Quick Guide to the VBA Array

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:

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

As you can see in the following example we are writing the same code five times – once for each student:

The following is the output from the example:

VBA Arrays

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:

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:

Next we compare assigning a value:

Finally we look at writing the values:

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:

  • Static – an array of fixed length.
  • 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:

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:

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:

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:

You can use it like this:

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.

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:

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.

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.

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.

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:

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:

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.

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:

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:

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:

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:

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.

You can use this function like this:

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.

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

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:

The following example creates a random value for each item in the array and the prints the values to the Immediate Window:

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
  • Enters j loop
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • Exit j loop
  • i is set to 1
  • 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

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

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:

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:

Assigning from one set of cells to another is also much faster than using Copy and Paste:

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.

The following is a summary of the main points of this post

  • Arrays are an efficient way of storing a list of items of the same type.
  • You can access an array item directly using the number of the location which is known as the subscript or index .
  • The common error “ Subscript out of Range ” is caused by accessing a location that does not exist.
  • There are two types of arrays: Static and Dynamic .
  • Static is used when the length of the array is always the same.
  • Dynamic arrays allow you to determine the length of an array at run time.
  • LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
  • The basic array is one dimensional . You can also have multidimensional arrays.
  • You can only pass an array to a procedure using ByRef . You do this like this: ByRef arr() as long.
  • You can return an array from a function but the array, it is assigned to, must not be currently allocated.
  • A worksheet with its rows and columns is essentially a two-dimensional array.
  • You can read directly from a worksheet range into a two-dimensional array in just one line of code.
  • 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.)

307 Comments

James

Hello Paul, I’m reading through your articles and I have one concern: what’s the best solution: 1. array of UDTs, 2. colection of UDTs, 3. dictionary of UDTs, 4. collection of classes 5. dictionary of classes? Let’s assume it is the big number of personal data with strings, numbers and dates. Thanks in advance.

Jothiboss

Hope you’re good!

I could see many Custom Toolbars with User defined functions in all of your videos. Can you please help to understand, how it was created..

* Eagerly waiting for a positive response Regards,

Jothiboss S

Richard Greenwood

hi paul In your arrays tutorial under the section; How To Make Your Macros Run at Super Speed, You copy data from a sheet range A1 to Z20000 to the student marks array. You then double the values in the first dimension and then write the array back to the original range again. Am I right in thinking that the values that have been doubled are in the first dimension which is the rows A1 to A20000. Your tutorial by the way is very helpful and has helped me understand arrays which has been useful in my work so thanks very much.

Paul Kelly

Hi Richard,

It will update column A. StudentMarks(i, 1) is column A, StudentMarks(i, 2) is column B as so on.

Richard HArkins

I have an Excel program that is calling a Word doc. I want the word doc to be “on top” when it opens. However, it isn’t and I am not finding any code that handles that matter. Suggestions?

Dick Harkins Scottsdale Arizona [email protected]

Charles Rogers

This Array information is great, question is I have a huge range of information(ie rows(8:450) & columns(A:AM) that I need to separated out by a specific column(M) value. Need I have written a simple copy paste routine and it works, but takes a long long time to perform. Am extremely interested in knowing if this Array method might be able to speed the system up.

Hi Charles,

Try it out on a small sample and compare the time. This video may help.

Graeme

What i have discovered is that as well as copy values using your super fast method, is that you can say:

DestinationRange.Formula = SourceRange.Formula DestinationRange.Style = SourceRange.Style

Which is pretty cool.

Rien

Hi Paul, I have a question about your “Range to Array” method Dim arr As Variant arr = Range(“A1:D2”) followed by your method of walking through the 2-Dimensional array For i = lbound(arr,1)… etc.

In stead of fixed, I need the range to be dynamic, so Dim rng as Range Set rng = Range(“A1:D2”) arr = rng

But since the range is dynamic, it can happen that sometimes it contains only one cell, eg Range(“A1”). Then it will not return a 2-dimensional array, but a single String. The consequence is that the for-loop can not be used, since the variant arr is not an array.

How can I force the result of arr = rng always to be a 2-dimensional array?

Maybe you can add this to your great guide, to make it even more complete. THANKS in advance, Rien, Netherlands

You can do something like this:

If Not IsArray(arr) Then arr = Range(“A1:D2”).Value ReDim Preserve arr(1 To 1, 1 To 1) End If

Lorn

The only thing missing is how to sort multi-dimensional arrays

Deon

Hi Paul. Thanks for the useful posts and videos. I have a set of data that looks like this: 48 rows, 3 columns. Columns 2 and 3 contain multiple comma delimited values, but of unknown quantities (anything between 0 and an upper limit of 100 comma delimited values per cell should suffice). My function needs to loop through the rows, then for each row perform a loop of LIKE operations for each comma delimited value in column 2, and (if the like is true) within that loop a NOT LIKE operation for each comma delimited value in column 3. Hope that makes sense. My question is: what data structure would you use for the data? A 3D array with lots of empty 3rd dimensions for column 2 and 3? Or can collections or a dictionary serve me better here? I have little experience of those last structures but I guess choosing the right one is the starting point. Thanks

Karsten Liebmann

thanks for the comprehensive description.

Questions I am puzzled by – can you help?

1. why does this not work (the values in the range are 0 to 10): Dim Numbers() As Integer Numbers = Range(“A1:L12”).Value 2. why does this not work (the row/column sizes are identical): Dim Numbers(0 to 11,0 to 11) As Variant Numbers = Range(“A1:L12”).Value

Peter Denney

additional way to create array’s you may want to add Sub pike_test() Dim dbArray() As Variant

‘1D array string conversion dbArray = [{1,2,3}] Range(“A1”).Resize(1, UBound(dbArray)).Value = dbArray

dbArray = [{“apple”,”bannana”,”mango”}] Range(“H1”).Resize(1, UBound(dbArray)).Value = dbArray

‘2D array string conversion dbArray = [{1,2;3,4;5,6}] Range(“A5″).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray

dbArray = [{1,”apple”;3,”bannana”;5,”mango”}] Range(“H5”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray

dbArray = [{1,2,3;4,5,6;7,8,9}] Range(“A10”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray

‘2D array string conversion with a string variable dbArray = Evaluate(“{1,2;3,4;5,6}”) ‘have to be more explicit, the shorthand won’t work Range(“E1”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray y = “{1,2;3,4;5,6}” dbArray = Evaluate(y) ‘have to be more explicit, the shorthand won’t work Range(“E5”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray

‘2D array string conversion with a string variable ‘ dbArray = Evaluate(“1,apple;3,bannana;5,mango}”) ‘have to be more explicit, the shorthand won’t work ‘ Range(“E10”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray ‘ y = “{1,apple;3,bannana;5,mango}” ‘ dbArray = Evaluate(y) ‘have to be more explicit, the shorthand won’t work ‘ Range(“E15”).Resize(UBound(dbArray, 1), UBound(dbArray, 2)).Value = dbArray

Ricardo Hernandez

Hello, i have a problem, when i assign a range to an array, the values in cells are different that values in array. the cells store filenames, some have accented chars á, what can i do in order to store the true filenames?

Armaan Khan

Your explenations are the best!

Is there a way to write a specific sub section of a 2D arry to a specifc range?

arr = ( 1 to 100, 1 to 3)

arr = ws1.range(“A2:C100”)

ws2.range(“A5:C50”) = arr(5 to 50, 1 to 3)

Its this last line that I can’t find a solution to. Array to Range seems a lot faster then going thru each element of the array and writing to a cell.

Keith Mefferd

Hi, Armann – this may be way late, but I would create a second array to contain the portion of the main array you want, then assign that smaller temporary array to the range.

Philippe Wuest

Thanks for your very helpful explanations on VBA arrays! They helped me solve a problem I had been struggling with for a long time. What I found confusing however, is the illustration of the difference between 1D and 2D arrays in the “Using a Two-Dimensional VBA Array” section. In the illustration the 1D array stretches over as many columns as the 2D array, which is in contradiction to your explanation or at least rather counter-intuitive. Or maybe, as a VBA newbie, I got it all wrong …?

That is correct Philippe. A 1D array is simply a 2D array with one row.

John Noriega

Thank you for that reply to Phillipe. I was going nuts trying to write a 1D array to a column of cells. It would only put the first value in the array in every cell. I finally scrolled down and read the comments here. “A 1D array is simply a 2D array with one row.” and the light bulb goes on! It’s treating rows in the range as rows in the array, so for each new row in the range it starts reading the array again. I reset the array from arr(24) to arr(24,0) and everything works. Perfect timing, too. I just ran into this yesterday.

Glad that helped John. I only replied to it yesterday.

Thomas

should this be split into 4 elements? –not 3

The following code will split the string into an array of three elements:

Dim s As String s = “Red,Yellow,Green,Blue”

Dim arr() As String arr = Split(s, “,”)

Yes, It was a typo that I just updated.

Joe

Hi Paul, What is happening when one does not use ReDim to set the length of a dynamic array? For example, in the below simple example, is ReDim implicitly called in the last line [e.g. arr = Split(s, “,”)]?

Similarly for the case of the variant array, is ReDim implicitly called?

Dim arr1 As Variant arr1 = Array(“Orange”, “Peach”,”Pear”)

Dim arr2 As Variant arr2 = Array(5, 6, 7, 8, 12)

In summary, my question is, when is ReDim required to set the length of a dynamic array and when is ReDim not required to set the length of a dynamic array ?

When you use a function like split or array it automatically creates the array for you so you don’t need to use Redim. When you are going to fill the array then you need to set the size using Dim or Redim. Redim allows using variables to set the size which makes it more flexible.

Andy

Hi Paul, Love your content and videos. I have a data set which is 7000 columns by 3000 rows. As an example I want to find the average of a subset of column A where values in column D meet are greater than a certain value and values in column Z are less than a certain value. Once I get the result I want to put this in a different worksheet. I am trying to process lots of values. Is this a job for arrays? Do I solve this thru a loop or what is the best way to write the averageifs function. Thank you so much!

cunky

hi paul, could you suggest me how to create (coding) for this : colomn F = colomn E + 1 without function looping for i=1 to n. because if i use looping for xxx.xxx rows it needs time to proceed.?

蘇孟緯

Submit a Comment Cancel reply

Your email address will not be published. Required fields are marked *

array assignment vba

You are not logged in

You are not currently logged in.

VBAF1

Automation Made Easy & Productive!

Assigning Values to an Array

VBA Assigning Values to an Array in Excel

VBA Assigning Values to an Array in Excel. An array values are assigned to an element based on an array index or subscript. Defining values for both static and dynamic array types are same. Let us see how to assign values to static and dynamic array.

Static Array Value Assigning

Dynamic array value assigning.

  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Let us see the example how to set values to static array. The array name is aArrayName and (0 To 2) means it stores 3 values.

Let us see the example how to set values to dynamic array. In the below example we used ReDim and Preserve keywords. ReDim statement is helps to define the array size during run time. And Preserve keyword helps to retain all existing elements in 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

Leave a Reply Cancel reply

You must be logged in to post a comment.

- Written by Puneet

  • Think of an array in VBA array as a mini database to store and organized data (Example: student’s name, subject, and scores).
  • Before you use it, you need to declare an array; with its data type, and the number of values you want to store in it.

If you want to work with large data using VBA, then you need to understand arrays and how to use them in VBA codes, and in this guide, you will be exploring all the aspects of the array and we will also see some examples to use them.

What is an Array in VBA?

In VBA, an array is a variable that can store multiple values . You can access all the values from that array at once or you can also access a single value by specifying its index number which is the position of that value in the array. Imagine you have a date with student’s name, subject, and scores.

You can store all this information in an array, not just for one student but for hundreds. Here’s a simple example to explain an array.

In the above example, you have an array with ten elements (size of the array) and each element has a specific position (Index).

So, if you want to use an element that is in the eighth position you need to refer to that element using its index number.

The array that we have used in the above example is a single-dimension array. But ahead in this guide, we will learn about multidimensional arrays as well.

How to Declare an Array in VBA

As I mentioned above an array is the kind of variable, so you need to declare it using the keywords (Dim, Private, Public, and Static). Unlike a normal variable, when you declare an array you need to use a pair of parentheses after the array’s name.

Let’s say you want to declare an array that we have used in the above example.

Steps to declare an array.

Quick Notes

  • In the above code, first, you have the Dim statement that defines the one-dimensional array which can store up to 10 elements and has a string data type.
  • After that, you have 10 lines of code that define the elements of an array from 0 to 9.

Array with a Variant Data Type

While declaring an array if you omit to specify the data type VBA will automatically use the variant data type, which causes slightly increased memory usage, and this increase in memory usage could slow the performance of the code.

So, it’s better to define a specific data type when you are declaring an array unless there is a need to use the variant data type.

Returning Information from an Array

As I mentioned earlier to get information from an array you can use the index number of the element to specify its position. For example, if you want to return the 8th item in the area that we have created in the earlier example, the code would be:

In the above code, you have entered the value in cell A1 by using item 8 from the array.

Use Option Base 1

I’m sure you have this question in your mind right now why we’re started our list of elements from zero instead of one?

Well, this is not a mistake.

When programming languages were first constructed some carelessness made this structure for listing elements in an array. In most programming languages, you can find the same structure of listing elements.

However, unlike most other computer languages, In VBA you can normalize the way the is index work which means you can make it begins with 1. The only thing you need to do is add an option-based statement at the start of the module before declaring an array.

Now this array will look something like the below:

Searching through an Array

When you store values in an array there could be a time when you need to search within an array.

In that case, you need to know the methods that you can use. Now, look at the below code that can help you to understand how to search for a value in an array.

  • In the first part of the code, you have variables that you need to use in the code further.
  • After that, the next part is to generate random numbers by using RND to get you 10 values for the array.
  • Next, an input box to let enter the value that you want to search within the array.
  • In this part, you have a code for the string to use in the message box if the value you have entered is not found.
  • This part of the code uses a loop to loop through each item in the array and check if the value that you have entered is in the array or not.
  • The last part of the code shows you a message about whether a value is found or not.

More on VBA Arrays

  • VBA Add New Value to the Array
  • VBA Array Length (Size)
  • VBA Array with Strings
  • VBA Clear Array (Erase)
  • VBA Dynamic Array
  • VBA Loop Through an Array
  • VBA Multi-Dimensional Array
  • VBA Range to an Array
  • VBA Search for a Value in an Array
  • VBA Sort Array

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Array function

  • 8 contributors

Returns a Variant containing an array .

Array ( arglist )

The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Variant . If no arguments are specified, an array of zero length is created.

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element.

In the following example, the first statement creates a variable named A as a Variant . The second statement assigns an array to variable A . The last statement assigns the value contained in the second array element to another variable.

The lower bound of an array created by using the Array function is determined by the lower bound specified with the Option Base statement, unless Array is qualified with the name of the type library (for example VBA.Array ). If qualified with the type-library name, Array is unaffected by Option Base .

A Variant that is not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types . Although a Variant containing an array is conceptually different from an array whose elements are of type Variant , the array elements are accessed in the same way.

This example uses the Array function to return a Variant containing an array.

  • Functions (Visual Basic for Applications)

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Was this page helpful?

Submit and view feedback for

Additional resources

Microsoft Excel

10 minute read

Excel VBA Array Tutorial

Alan Murray

Alan Murray

Twitter LinkedIn WhatsApp Pocket Email

array assignment vba

Join the Excel conversation on Slack

Ask a question or join the conversation for all things Excel on our Slack channel.

Excel VBA arrays are a crucial skill to master when learning VBA in Excel.

An array in VBA is a special type of variable that can store multiple values of the same data type. By using arrays, you can read and manipulate a list of data faster than if it were stored in an object such as a range or table.

In this tutorial, we will see multiple Excel VBA array examples to gain insight into how to use the different types of arrays.

Download the sample file to practice along with the tutorial.

Download your free VBA practice file!

Use this free Excel file to practice along with the tutorial.

What is an Excel VBA array?

We learned about different types of variables earlier in this VBA series, but the variables in that tutorial could only store a single value. An Excel VBA array can store a list of values of the same data type.

VBA arrays can be one-dimensional or two-dimensional, and we will see examples of both in this tutorial. Also, the number of items stored in an array can be fixed or dynamic.

Each item in an array is assigned an index. This is its position within the array and can be used to read and manipulate the value. By default, arrays start with an index value of 0. So, the first item in an array is position 0, the next is position 1, and so on.

Declare a VBA array

When you declare an array in Excel VBA, you specify its size and data type.

For example, we have the following range of data containing values for each month of the year. So, for this dataset, we know that there are 12 values.

Chart-of-months-and-values

The following code declares an array variable named MonthValues that contains 12 elements and has the Currency data type.

Remember, arrays, by default, use base 0 indexing. So although there are 12 elements in the array, its upper bound is 11. The upper bound is the last index position.

In the following code, the Option Base statement is inserted at the top of the module. This specifies to use of base 1 indexing in the module. The upper bound of the array is 12 in this instance.

An alternative, and easier method, is to set the lower and upper bound of the array when declaring the variable using the To clause.

Using this method, the boundary size of the array is clearer to anyone using your VBA code .

You can set the lower bound to any value. For example, you could have specified 5 To 16 for the array size, but that would have been strange for this example.

You do not always know the length of an array in advance. So, for these instances, you create a dynamic array by omitting the array length when declaring.

You can then use the keyword Redim when you are ready to set the VBA array length.

Using month values may seem like an odd choice to use for a dynamic array, but not all 12-month values may be available at a given time in the procedure.

Populate array with cell values

Once an Excel VBA array has been declared, you will want to populate it with cell values or constant values that you know already.

For example, let’s imagine that we want to populate an Excel VBA array of strings with the month names. The following code uses the Array function to assign the string values to the array.

It is important for this technique that the array variable is of a Variant data type. It has also been declared as a dynamic array with no size specified during its declaration.

In the following image,  we have stepped into the code (link to debugging article), and the Locals window shows the month names assigned to the array. Notice that the index starts from 0.

Highlighting-end-sub

So, this is useful to know, but it is more likely that you will need to populate an array from cell values.

For this example, we will populate the array with the month values stored in the range B2:B13. A For Next loop will be used to assign a value to each index of the array.

If you need to change the value for a specific index position, you can reference this explicitly.

In the following example, the index position (or subscript) to change is provided by the value in cell D2. An arbitrary value of 10 is assigned to that index of the array.

If you provide an index that does not exist, the Subscript out of Range error is shown.

Subscript-out-of-Range-error

Excel VBA dynamic arrays

A dynamic array in Excel VBA is an array whose size can be changed during the execution of the sub or function .

We briefly saw how to declare and re-dimension a dynamic array earlier in this tutorial. Let’s visit them in more detail now.

When looping through the elements of an array to read, change, or print its values, you need to specify the first and last element in the array. So, you may be wondering how to do this with a dynamic array.

Thankfully, there are the LBound and UBound functions in Excel VBA for this task.

In the following code, the array is populated with the values from range B2:B13, just as in a previous example.

However, the LBound and UBound functions are used in the For Next loop in place of the fixed values of 1 and 12 used previously. This is the most effective way to loop through the elements of an Excel VBA array.

In this example, the size of the array is specified by the value in cell D2. The code will work without knowing the value entered. The code would continue to operate regardless of the range ending in cell B5, B8, or B13.

You may also notice that Option Base 1 was specified to ensure that the array started with an index of 1.

If you need to change the size of the array later, the ReDim keyword can be used again to re-dimension the array.

When changing the array size again, all existing values assigned to the array are lost unless the Preserve keyword is also used.

Excel VBA arrays and ranges

When populating an array with values from a range, you can pass all range values directly to the array without looping through its elements.

In the following code, the month values in range B2:B13 are assigned to the MonthValues array in a single statement. It is essential that the array is of a Variant data type.

The values of the array can be printed to a range in the same manner. The following statement prints the values to range C2:C13 of a sheet named “Archive”.

Note the range was specified explicitly. A loop between the LBound and UBound elements of the array could have been deployed instead of this explicit reference.

Two-dimensional Excel VBA arrays

All the examples so far have used one-dimensional arrays. Before we finish this tutorial, let’s see an example of a two-dimensional VBA array.

In the following code, the range A2:B13 has been assigned to the array named MonthData . This has created a two-dimensional, 12-by-2 array. It is twelve rows high and two columns wide.

If a one-dimensional array is a list of values, then a two-dimensional array is a list of lists.

In the following image, the Locals window shows the values stored in the array. The first two rows are expanded to show that each row index contains two values.

Two-dimensional-array

Excel VBA arrays can handle up to 60 dimensions, so they can store much larger datasets than are demonstrated here.

To retrieve data from a specific position in the two-dimensional array, the row, and column index would need to be given. For example, the following two statements print the values from both columns of row 1 into cells F2 and G2, respectively.

If we wanted to manipulate each value in the array, or a specific dimension of the array, a For Next loop could be used.

In this example, a For Next loop is used to multiply each element in the second column of the array by 20%.

In this example, the two-dimensional Excel VBA array was created by assigning a range to it, a cool technique. However, it is important to know how to specify the size of the array when you declare it.

In the following code, the row and column dimensions' lower and upper bounds are given when declaring the array.

To populate the array from cell values using a loop, a nested For Next loop is required to loop through each list within a list (or columns for each row).

The counter variables are named r for the row index and c for the column index, respectively, to make them easy to identify.

The loop for the two columns of the array is nested within the outer loop for the rows of the array.

Once you are familiar with looping structures such as this, they can be easily adapted for other arrays. The variable aspect of this framework is the use of the Cells object to retrieve data from the sheet.

Learn Excel VBA today?

Learning how to use Excel VBA array variables is very important if you want to master Excel VBA. Yet, there is so much more to learn.

Enroll in our Excel macros and VBA online course to fast-track your VBA skills. It contains 41 practical lessons to master all the Excel VBA fundamentals.

Level up your Excel skills

Become a certified Excel ninja with GoSkills bite-sized courses

Loved this? Subscribe, and join 430,173 others.

Get our latest content before everyone else. Unsubscribe whenever.

Alan Murray

Alan is a Microsoft Excel MVP, Excel trainer and consultant. Most days he can be found in a classroom spreading his love and knowledge of Excel. When not in a classroom he is writing and teaching online through blogs, YouTube and podcasts. Alan lives in the UK, is a father of two and a keen runner.

Top 12 Excel Lookup Functions (+ Free Cheatsheet!)

Recommended

Top 12 Excel Lookup Functions (+ Free Cheatsheet!)

Learn how to use the top 12 Excel lookup functions and download a free cheatsheet to keep for easy reference.

Understanding Excel VBA If Then Else Statements

Understanding Excel VBA If Then Else Statements

Get a comprehensive overview of the If Then Else statement in Excel VBA and its different syntaxes.

Excel Challenge 34: Advanced Data Validation

Excel Challenge 34: Advanced Data Validation

Flex your data validation and worksheet protection skills with this month's Excel challenge.

© 2023 GoSkills Ltd. Skills for career advancement

ExcelDemy

Excel VBA Multidimensional Array for Assigning Values (6 Ways)

Avatar photo

Arrays are data structures that allow you to store and manipulate large amounts of data in a single variable. They are particularly useful when dealing with large datasets or when performing calculations on multiple values at once. In this article, we’ll use Excel VBA Multidimensional Array for Assigning Values. Here we will cover the types of arrays in VBA, the procedures of assigning values to the multidimensional array, ways to reform array size, uses of multidimensional arrays, sorting array values in Excel, etc.

Want to get a quick illustration of the article we are working with? The following video will illustrate our purpose and help to get you an overview of assigning values to the multidimensional array.

How to Launch VBA Editor in Excel

For executing VBA, you need to activate the Developer tab on the Ribbon if you haven’t done it before. After launching the Developer tab on the Home screen, launch the Visual Basic Editor window.

  • Go to the Developer tab and select Visual Basic under the Code .

Activate Visual Basic Editor window with Developer tab in Excel

Alternative command : Pressing ALT+F11 will also take you to the VBA window.

There are 3 ways to insert code in the Visual Basic Editor window.

1. Using Module Window

  • Now, the Visual Basic Editor window will show up on the screen. Click the Insert tab of the VBA window and select Module .

Insert Module in the Excel VBA window

  • You will see a Module window has popped up right beside the Project – VBAProject You have to insert the code you want to execute in this window.

Module window for inserting VBA code in Excel

You can either use multiple Modules for different Macros or insert your Macros one after another in the same Module . If you have different macros for serving different purposes, then it is preferable to use different Modules as it will help find your macros quickly.

2. Utilizing Sheet Code Window

Besides the Module window, you can utilize the Sheet Code window.

  • After opening the Visual Basic Editor , right-click on the sheet name.

Right-click on the sheet name to activate code window

  • From the menu, select the View Code .

Select the View Code option from the menu

  • You will see the Sheet (Code) window has appeared on the screen.

Sheet (Code) window for inserting VBA code

Note : The code inserted in the sheet code window only works for that specific sheet.

3. Adding Button for Macro

Another way to insert VBA code is to add a Button . By adding a button and assigning Macro to that button, you can faster and automate your task.

Introduction to Array in Excel VBA

In Excel VBA, an array is a collection of values of the same data type that are stored in a contiguous block of memory. Arrays are used to store large amounts of data in a compact and organized manner and can be useful for performing complex calculations or data manipulations.

Arrays can be categorized based on two factors.

i) By Dimensionally: Arrays can be either single-dimensional (also called one-dimensional) or multi-dimensional.

ii) By Sizing: Arrays can be either static or dynamic.

Based on Dimension

1. one-dimensional array.

In Excel VBA, a one-dimensional array is a collection of related data values stored in a single row or column of cells. It is essentially a list of values that can be accessed using a single variable name. To create a one-dimensional array in Excel VBA, you can declare it using the Dim statement, specifying the data type of the elements and the number of elements in the array.

One dimensional array example

2. Multi-Dimensional Array

In Excel VBA, a multidimensional array is a collection of related data values stored in multiple rows and columns of cells. It is essentially a table of values that can be accessed using multiple variable names.

Example of multidimensional array

Read More: Excel VBA Multidimensional Arrays

Based on Size

1. static array.

The default array size starts from 0. If an array with size 2 means that it can store 3 values at a time. A Static array has a fixed number of elements and a fixed size, which is determined at the time of declaration. Once the size of the array is set, it cannot be changed.

Static array example

The image above describes that the array has a size of 3 which means it can’t store values of more than 3.

2. Dynamic Array

A dynamic array is an array that can be resized during runtime. In contrast to a static array, where the size is determined at compile time, a dynamic array can be resized based on the current needs of the program.

To create a dynamic array in VBA, you first declare the array without specifying a size.

Dynamic array with ReDim statement

After that, declare the array size with the ReDim statement.

How to Declare a Multidimensional Array in Excel VBA

In Excel VBA, the array is declared with the Dim command at the beginning of the subprocedure. For a multidimensional array, you have to use commas to separate each dimension.

Declare a multidimensional array

This creates an array called SalesData with 5 rows and 2 columns, where each element of the array is a variant (integer or string).

Read More: Excel VBA to Declare Multidimensional Array of Unknown Size

Excel VBA Multidimensional Array for Assigning Values: 6 Suitable Examples

So far you have learned about multidimensional array and the way to declare it. You can assign values to your multidimensional array based on your requirements and situations. You can assign values to your declared array, erase the value, resize the array, and also preserve the previous value after resizing the array.

1. Populating Excel Sheet by Assigning Values Directly Inside Code

You can just directly assign values to your array with the relevant dimension index and use this array to populate your Excel sheet with the array values. Here’s a sample example of populating a worksheet with array values assigned in code directly.

Assign values to multidimensional array directly in VBA code

Read More: Excel VBA to Populate Array with Cell Values

2. Assigning Values to Array from One Sheet to Another

When you don’t want to assign values to your array within code directly, rather you need to assign values to the array from worksheet data, in that case, this method is useful. The VBA code used here will hold the array values by reading data from one worksheet and then populating another one.

VBA code for assigning values to array from one worksheet

Code Breakdown

The code copies data to the array from the source range ( “B4:F8” ) of the source worksheet “Directly” to the destination range ( “B4:F8” ) of the destination worksheet “Another Sheet” .

3. Applying “For” Loops to Assign and Display Multidimensional Array Values

In Excel VBA, the For loop is used to iterate over a block of code a specified number of times. The For loop can be used to perform repetitive tasks, such as iterating over a range of cells, performing calculations on each cell, and storing the results in another range.

3.1. Using Range Object for Assigning Values to Array

The Range object in Excel VBA represents a cell or a range of cells in a worksheet. A range can be a single cell, a row, a column, or a rectangular block of cells.

Let’s see an example of a multidimensional array using the “For” loop with the “Range” object.

Here, an array will be created by multiplying the current Row and Column index number with the loop.

VBA code with application of Range object with For loop

The code writes the values of the myArray to a range of cells in the worksheet. The Range object is used to specify the range of cells B4:E6 where the values should be written. The Cells property is then used to select the appropriate cell within the range, based on the current value of i and j.

The code will show the result below after executing.

3.2. Utilizing UBound and LBound Functions

In Excel VBA, UBound stands for “Upper Bound” and returns the highest available index number and LBound stands for “Lower Bound” and returns the lowest available index number for a specified array dimension.

The code below utilizes VBA UBound and LBound functions and returns the same result gained with Method 3.1.

Use of UBound and LBound functions in VBA for assigning values to array

The code first fills the array values with the predefined size using the UBound and LBound functions and prints the array values in the range “ B4:E6 ”. In this way, we can have VBA multidimensional array for assigning values.

Read More: How to Use UBound on Multidimensional Array with VBA in Excel

4. Assigning New Values to 2D Dynamic Array with “ReDim” Statement

Consider the scenario above where we have values that we can utilize for a 2 Dimensional array. Inserting the array name with a blank parenthesis is used to make the array size dynamic. Applying the ReDim statement afterward fixes the size. The ReDim statement is used to change the size of an existing dynamic array at runtime. But applying the ReDim statement changes the size of an existing array and assigns new values to the array.

Consider the following example where a dynamic array is declared with Dim Arr() syntax and the size of the array is declared 3×2 with the ReDim Arr(0 To 2, 0 To 1) statement.

ReDim statement for assigning new values to array in VBA

In this code, the array size is not declared first with the Dim Arr() statement. Next the ReDim Arr(0 To 2, 0 To 1) statement is applied to define a 3×2 array, and the values are assigned to the array. You can show a random array value with MsgBox to check whether the new values are really encountered or not.

ReDim statement clears the previous array and assigns a new array. If the ReDim statement is encountered again, it will clear the previous array value and create a new array. If no values are assigned again, the array will hold nothing.

Resize array with ReDim statement in VBA

This time the second ReDim will clear the value assigned with the first ReDim .

5. Preserving Previous Data with 2D Dynamic Array Using “ReDim Preserve” Statement

The ReDim statement clears the previous array values keeping the memory blank. But sometimes you may need to increase the array size but keep the previous array values in memory. If you use the ReDim statement again, it will redefine the size as well as potentially clear array values. In that case, the ReDim Preserve statement is a lifesaver. It not only resizes the array but also keeps the previous value at the same time.

Resize the array to add another row with storing the previous value

Here, one thing that should be kept in mind is that you can only resize the second dimension of the 2D array with ReDim Preserve . If you try to change the first dimension, it will show you a Run time error .

Unavailability of resizing first dimension of multidimensional array

If you had a 1-dimensional array with 10 elements, you could use Preserve to keep the first 5 elements and add 5 more elements to the end of the array. However, you have seen that this functionality is not available for multi-dimensional arrays.

To resize a multi-dimensional array while preserving the existing data, you’ll need to create a new array and copy the values from the old array to the new array. Here’s an example of how you can do this.

Resizing first dimension of a multidimensional array

This will resize the first dimension and show the value in the message box.

Read More: How to Redim 2D Array with VBA in Excel

6. Assigning New Values to 3D Array

A 3D array in Excel VBA is a data structure that consists of three dimensions. By using a 3D array in Excel VBA, you can efficiently store and manipulate large amounts of data in a three-dimensional format. In VBA, when you declare an array with fixed dimensions that cannot be changed afterward. However, you can modify the values of the individual elements within the array without changing the array’s size using the index number of the array element. The code below demonstrates how to work with 3-dimensional arrays in Excel VBA and how to assign new values to specific elements of the array.

Assign new values to 3Dimensional array

After initializing the array, the code assigns new values to three specific elements of the array. The element at position (0,0,0) is assigned a value of 100, the element at position (1,1,1) is assigned a value of 200, and the element at position (2,2,2) is assigned a value of 300.

Finally, the code displays a message box showing the value of the element at position (1,1,1), which should be 200.

How to Use Multidimensional Array in Excel VBA

From the above dataset, we will find sales for a specific product , Region   and quarter   (Q1/Q2/Q3/Q4).

VBA code to get specific array value from dataset

The code will take input in the input box and show output in message box.

How to Reset Array Values to Default in Excel VBA

The VBA Erase function clears all the array values.

How to Get Length of Multidimensional Array in Excel VBA

There might be a situation where you will need to get the length of an array. In that case, the following code can get you on the way.

VBA code to get the array length

Read More: VBA to Get Array Dimensions in Excel

How to Use Array and Split Functions Together to Separate Values in Excel VBA

When you have multiple strings in one cell and you want to split the string and put them in distinct cells, use the following VBA code.

VBA code to separate array values

How to Sort Multidimensional Array in Excel VBA

When you need to take an array from a worksheet and sort the array, this method is useful in that case.

VBA code to sort array value in worksheet

Advantages of Using Multidimensional Array

  • Multidimensional arrays allow you to organize data in a more structured and intuitive way.
  • Using multidimensional arrays in Excel VBA can improve performance by reducing the number of loops and iterations in your code.
  • Multidimensional arrays can simplify your code by allowing you to perform operations on multiple dimensions of data at once, rather than having to loop through multiple one-dimensional arrays.
  • Multidimensional arrays in Excel VBA are highly flexible and can be used in a wide variety of applications, including data analysis, financial modeling, and simulation.

Overall, multidimensional arrays in Excel VBA provide more flexibility and organization than one-dimensional arrays, allowing you to access specific cells of the table using row and column index numbers.

Takeaways from This Article

  • To declare a multidimensional array in VBA, you need to specify the number of dimensions and the size of each dimension.
  • You can assign values to a multidimensional array in VBA using nested loops that iterate over each dimension of the array.
  • You can use the LBound and UBound functions to determine the lower and upper bounds of an array.
  • You can use the ReDim statement to resize a multidimensional array. When you resize an array, you can preserve the existing values by using the ReDim Preserve .

Things to Remember

  • The default array index in Excel VBA is 0 for all dimensions of the array. You can start the array index from 1 by declaring it.
  • The ReDim statement only changes the second dimension of the array. If you try to change the first dimension, the code will show you a Run time error after execution.

Frequently Asked Questions

  • How do you access an element of a multidimensional array?

To access an element of a multidimensional array, you need to specify the indices for each dimension of the array. For example, if you have a two-dimensional array named “ myArray ” with dimensions 1 to 3 and 1 to 2 , you can access the element in the second row and first column using the myArray(2,1) syntax.

  • How data is stored in a multidimensional array?

In a multidimensional array, data is stored in a tabular format, where the first dimension represents the rows and the second dimension represents the columns.

Download Practice Workbook

You can download our practice workbook from here for free!

In this article, we have learned about Excel VBA multidimensional array for assigning values directly, populating one sheet from another, resizing size and preserving array values, and clearing array. Array has diversified use in Excel VBA. The necessity will tell you what you should use in your particular case.

Related Articles

  • Excel VBA 2 Dimensional Array Initialization
  • How to ReDim Preserve 2D Array in Excel VBA

What is ExcelDemy?

Tags: VBA Arrays

Rafiul Hasan

Hey there! I am Md. Rafiul Hasan. Currently, I am working as an Excel & VBA content developer. I like new ideas and want to explore the field of innovation. Excel has saved our work time and made it easy for us to perform quick calculations. I am trying to make it easier for you to overcome the obstacles you face while working on Excel. Stay connected!

Leave a reply Cancel reply

ExcelDemy is a place where you can learn Excel, and get solutions to your Excel & Excel VBA-related problems, Data Analysis with Excel, etc. We provide tips, how to guide, provide online training, and also provide Excel solutions to your business problems.

Contact  |  Privacy Policy  |  TOS

  • User Reviews
  • List of Services
  • Service Pricing

trustpilot review

  • Create Basic Excel Pivot Tables
  • Excel Formulas and Functions
  • Excel Charts and SmartArt Graphics
  • Advanced Excel Training
  • Data Analysis Excel for Beginners

DMCA.com Protection Status

Advanced Excel Exercises with Solutions PDF

ExcelDemy

Learn VBA in Excel: These 11+ Tutorials Teach You VBA in 20 Hours

Written by co-founder Kasper Langmann , Microsoft Office Specialist.

It’s only natural. VBA is a huge topic . 

Naturally, questions like “Where do I start? Where does it end? What should I focus on?” will arise.

Without a plan, learning VBA will be hard.

That’s why we made this ultimate tutorial, to teach you how you can start writing code from scratch! We’ve collected more than 11 of the best tutorials around the web you can bounce if you would like to know more.

Excited? Let’s get started! 😊

Table of Content

Chapter 1:   Introduction to VBA and Macro

Chapter 2:   The VBA Editor

Chapter 3:   Modules and Subs

Chapter 4: Variables

Chapter 5:  Logic and Boolean

Chapter 6: Do Loops

Chapter 7: User Interaction

Chapter 8:  Error Handling

Chapter 9:  Where to go from here…

Getting started with VBA and Macro

The terms “VBA” and “Macro” are often used interchangeably .

And that’s okay! Why? Because more or less, when someone mentions either word, they actually mean the same thing.

But looking more inwardly, what’s VBA and Macro?

VBA is short for “Visual Basic for Applications” . It’s a programming language created by Microsoft that comes pre-installed with Microsoft Office applications like Excel, Word, Access, and Outlook.

Macro, on the other hand, is sort of a series of instructions that perform a series of tasks . A macro is also referred to as a subroutine (sub) or a procedure .

At the end of this tutorial, our objective is for you to be able to create a sub, which is a collection of lines of VBA code that performs a task.

To aid with that, we included at the end of every section what we call “recommended readings” where you can read more about certain topics.

This tutorial serves only as a crash course. Treat it like a blueprint of topics you should learn so you would be able to learn Excel fast.

If you would like to invest a bit more and become a pro within 20 hours , we have a “VBA Masterclass” program . 

The beauty and advantage of this program are summarized in its 3 pillars: 

  • Actionable real-life training
  • High-level support and feedback
  • Interactive skill-assignments 

Otherwise, this tutorial is good enough for you. 😊

The Visual Basic Editor

The Visual Basic for Applications editor is where you create , manage , and run VBA code on your Excel spreadsheet.

If you’re familiar with programming, the VBA editor actually looks like an IDE (integrated development environment).

Here’s how the VBA editor looks like:

If you’re new to Excel, you might’ve noticed that you can’t see anything related to Visual Basic in the Ribbon.

The reason for this is, there are certain steps you have to take to be able to see and use the VBA editor.

First of all, you need to be able to see the ‘Developer’ tab.

Here’s a summary of how you can add the ‘Developer’ tab to your tab list:

  • Access the backstage view of Excel by clicking ‘File’ from the tab list.
  • Then, click ‘Options’ .
  • Click ‘Customize Ribbon’ on the left-hand sidebar.
  • On the right side of the screen, you’ll see the “Main Tabs” section. Check the ‘Developer’ box.

After that, a new tab will be added to your tab list.

To open the VBA editor:

  • Click the ‘Developer’ tab from your tab list.
  • Click the ‘Visual Basic’ icon under the ‘Code’ group.

After that, you’ll immediately see the VBA editor pop up!

Now that you have the VBA editor up and running, it’s time for some action!

Recommended Readings:

  • How to Use the VBA Editor in Excel (3 mins. reading time)
  • Visual Basic Editor – How to Open and Use it in Excel (16 mins. reading time)

Warming up with Modules and Subs

The lines of code in VBA is called a “sub” . Subs are stored in modules .

You need to know how to create modules so you have a place to store the subs or your lines of code.

Here’s a summary of how to create a module:

  • On the upper-left side of your VBA editor, you’ll see a tab titled “Project – VBAProject”. Below it, right-click on either ‘Sheet1 (Sheet1)’ or ‘ThisWorkbook’ .
  • Click ‘Insert’ from the options.
  • Click ‘Module’ from the options.

What you just did is already 50% of the work!

With a module on, all that’s left is for you is to write your first VBA code!

Let’s have you write your first 2 codes:

  • Sub WriteValue
  • Sheet1.Range(“A1”) = “Hello World!

Write down the first one, “Sub WriteValue” on your module and press “Enter” . Immediately, you’ll see another line of code pop up at the bottom, “End Sub” .

Now, write the second code, the popular “Hello World!” between the first code and the code that just popped up.

Just a little explanation about the code your writing:

What the code indicates is to write the value (right side) on the specified location (left side) which is cell A1 of Sheet1.

Here’s how the module will look like:

To see how your code will affect the worksheet, you’ll have to run it first:

  • On the VBA editor, click the ‘Run’ tab.
  • Then, click ‘Run Sub/UserForm’ .

Actually, you can press ‘F5’ to run the sub right away. 😊

Try and see your worksheet.

You’ll now be seeing this:

Congratulations! You just run your first code!

How long has it been since you started this tutorial? A few minutes? An hour? And now, you’ve already written your first code.

As you might have guessed, you can tweak the codes to display whatever text you like in any cell inside the worksheet. Feel free to try it! ✍

  • How to insert and run VBA code in Excel – tutorial for beginners (2 mins. reading time)
  • How to Use Ranges in VBA (5 mins. reading time)
  • The Complete Guide to the VBA Sub (14 mins. reading time)

Playing with Variables

The same with other programming languages, variables are vital in VBA.

If you’re not familiar with variables, here’s a good definition:

A variable stores a value. It stands in the place of a value.

There are 3 things you can do with a variable:

  • Declare or create a variable
  • Store a value in a variable
  • Read the value in the variable

Also, there are lots of different types of variables. The most common are:

  • String – for text
  • Long – for integers
  • Double – for decimals
  • Date – for date and time
  • Currency – similar to decimal but only up to 4 decimal places
  • Boolean – for true or false

When creating a variable, you’ll have to use “Dim” which is short for dimension . It tells Excel that the next word is the variable name.

Then, you’ll have to use “As” as the declaration statement . It tells Excel that you’re going to use that data type for that variable.

As an example, let’s say you would create a variable called “company” which is a string of text .

Then, to set the variable, you’ll need to create a line that assigns a value.

In VBA, all you have to do is append “.Value” to the variable and put an equals (=) sign pointing to that value.

Here’s how it would look like in your VBA editor:

Easy, right? Don’t worry too much about variables and data types. As long as you know the basic ones, you’ll be fine!
  • VBA DIM: How to Declare Variables in VBA (4 mins. reading time)
  • Excel VBA Variables, Data Types & Constant (4 mins. reading time)

Dealing with VBA Logic and Boolean

This section includes both the logical operators you can use in Excel VBA as well as the IF statements.

First off, there are 4 logical operators in VBA:

These operators are usually used in tandem with boolean statements or expressions.

Knowing how to use the IF statements in VBA will make your life easier.

Why? Because IF statements has always been an important concept in programming. These conditional clauses will help you accomplish almost anything.

There are 3 typical conditional expressions in VBA:

  • IF-THEN-ELSE

Here’s an example of how it works:

Suppose you’re using VBA to check a cell and see if the number is even. With that, we’re using this syntax:

If you put 24 on cell A1, you’ll see a message box like this:

You would need more practice in this part. Knowing the operators and the boolean clauses are only half the battle.

Knowing how to use them and when is what you’ll have to master.

  • How to Use IF Statements in VBA (6 mins. reading time)
  • Logical Operators in Excel VBA (5 mins. reading time)
  • Excel VBA IF THEN Statement (and a useful tip) (6 mins. reading time)

The Magic of Do Loops

Loops are easy to understand. But they get complicated real fast.

From the name itself, do loops allow you to run a command multiple times or repeat the command until specific criteria are met .

There are three types of “loop”:

  • Do Until Loop
  • Do While Loop

Here’s an example of how a for loop works:

This code will start a loop and write numbers 1 to 5 and stops at that last number:

Mind you, this is just a simple for loop code.

Once you learn how to make more complicated loops, you’ll start to see how much more you can do with a loop!
  • How to Use For Loops in VBA (5 mins. reading time)
  • VBA Do Loop (5 mins. reading time)

Allow User Interaction by Input Boxes

Pretty sure that by now, you have realized how Excel VBA can greatly affect your productivity using Excel.

With only a few lines of codes, you could save yourself an hour of work!

But here’s a question:

What if you want to get information directly from the user?

Yes! Input boxes are the way to do it.

Input boxes are like message boxes where users can enter information. You can then use that information directly on your macro.

For example, we would like to know how many hours you have practiced VBA since you started.

Here’s its code:

On the worksheet, a message box will appear:

Awesome, right?

With input boxes, you can store input from user entries that can be used in a macro.
  • Using an Input Box to Gather Data in VBA (4 mins. reading time)
  • VBA – InputBox (2 mins. reading time)

Don’t Be Afraid of Errors

No one is expected to write perfect code all the time. Sooner or later, you will experience errors.

That’s why it’s vital that you should learn about error handling.

Error handling is a practice of anticipating and writing codes to handle errors that happen in running applications.

Here are the 3 types of errors in VBA:

  • Compilation

How do you know when there’s an error?

The good thing is, the VBA editor will prompt you when there’s an error in your code.

Here’s an example of how a compilation error looks like:

Knowing the type of error that occurred is already half of the puzzle.

Of course, you don’t have to learn every possible error there is at once! Just learn on the go. Errors will pop up here and there.

Little by little, you would experience a lot of errors in VBA. And every instance will be a learning experience for you. 😊
  • Error Handling In VBA (7 mins. reading time)
  • VBA Error Handling – A Complete Guide (22 mins. reading time)

Where to go from here…

You might be wondering why we said you’ll learn VBA in 20 hours when in fact, adding all the reading time of every tutorial we recommended, only sums up to an hour and 45 minutes.

As with any computer programming language, learning the theory and principles is the easiest part. Correct practice and repetition are the ways to master VBA.

Our advice to you is to spend the remaining 18 hours to practice. If you do so, becoming a VBA pro will be at your arm’s reach! 🥉

IMAGES

  1. VBA Dynamic Array

    array assignment vba

  2. VBA Example: Sort Array Function

    array assignment vba

  3. Eng. Shady Mohsen blog: Excel VBA array of collections

    array assignment vba

  4. VBA Array Function in Excel

    array assignment vba

  5. How to use the ARRAY function [VBA]

    array assignment vba

  6. Array Assignment Help Online From Logical Programming Experts

    array assignment vba

VIDEO

  1. 2080 Mangsir 10||NID||सामान्यज्ञान र समसामयिक अध्ययन || Subjective|| Live Class ||By:-Sarthak Mahara

  2. VBA Excel Using Arrays and Listbox Excel

  3. VBA & Excel Lesson 3: Arrays Picking Up Ranges from Excel

  4. Array assignment

  5. SGD113

  6. SGD 113 Array Assignment

COMMENTS

  1. Using arrays (VBA)

    Option Base 1 Dim curExpense (365) As Currency You can also explicitly set the lower bound of an array by using a To clause, as shown in the following example. VB Dim curExpense (1 To 365) As Currency Dim strWeekday (7 To 13) As String Storing Variant values in arrays There are two ways to create arrays of Variant values.

  2. Excel VBA Array

    Excel VBA Array - The Complete Guide by Paul Kelly | | Data Structures VBA, Most Popular | 307 comments 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.

  3. VBA

    What is a VBA Array Variable? A VBA array variable can be thought of as a group of variables, stored under the same name and having the same data type. An array can store text, numbers, or objects. You refer to an element in an array using its index number.

  4. How to assign an array of values to a range in Excel VBA

    Works for assigning across columns in a given row. But Range("A1:A2") = Array("a","b") assigns "a" to both A1 and A2.I assume the Array needs to be 2-dimensional, but Array only appears to support creation of 1D arrays. ... Assigning range to array in VBA. 7. Using VBA to assign range of cell values to array of variables. 2. Assigning worksheet ...

  5. VBA Arrays

    Reviewed by Last updated on October 18, 2021 In this Article VBA Array Quick Sheet Arrays VBA Array Quick Examples Array Benefits? - Speed! Create / Declare an Array (Dim) Static Array Dynamic Array ReDim vs. ReDim Preserve Declaring Arrays Simplified Set Array Values Get Array Value Assign Range to Array Output Array to Range

  6. Assigning Values to an Array in Excel VBA

    Static Array Value Assigning. Let us see the example how to set values to static array. The array name is aArrayName and (0 To 2) means it stores 3 values. 'VBA Assigning Values to an Array Sub VBA_Assigning_Values_to_Array () 'Declare an Array variable Dim aArrayName (0 To 2) As Integer 'Set the value of array index 0 aArrayName (0) = 5 'Set ...

  7. How to Use VBA in Array: Master the Basics in 3 Minutes (Excel)

    Assigning Values to an Array Once you have declared an array, you can assign values to it. This is done using the array name followed by an index in parentheses. For example, 'arr (0) = 1' assigns the value 1 to the first element of the array. You can also assign values to an array using a loop.

  8. Declaring arrays (VBA)

    VB ' Integer array uses 22 bytes (11 elements * 2 bytes). ReDim MyIntegerArray (10) As Integer ' Double-precision array uses 88 bytes (11 elements * 8 bytes). ReDim MyDoubleArray (10) As Double ' Variant array uses at least 176 bytes (11 elements * 16 bytes). ReDim MyVariantArray (10) ' Integer array uses 100 * 100 * 2 bytes (20,000 bytes).

  9. How to use Array in VBA in Excel (Easy to Follow Guide)

    Steps to declare an array. First, use the keyword "Dim", enter the name of the array, and type parentheses. Next, you need to specify the data type for the array. If you do not have any data type specified VBA will assign appropriate data type. After that, you need to define the number of items that you want to store in the array.

  10. VBA Assign Range to Array

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

  11. VBA Array of Objects

    Using the Object Array in VBA Code. Once we have populated the Worksheet array, we can use VBA to loop through the array. Sub TestObjArray() 'define the array as a worksheet array Dim arWks() As Worksheet 'count how many worksheets in the file, and re-dim the array Dim n As Integer Dim i As Integer 'count the sheets and minus one to set the ...

  12. VBA Arrays

    VBA Arrays Article by Ashwani Jaiswal Reviewed by Madhuri Thakur Updated April 8, 2023 Excel VBA Arrays In VBA, an array is a memory location which is capable of storing some value or more than one value in it. There are 3 types of arrays in VBA, One Dimension, Two Dimensions and Multi Dimensions.

  13. Can't assign to an array

    Overview Dialog boxes Menus and commands Toolbars Window elements Error messages Overview A compatible ActiveX component must be a Visual Basic executable or a DLL A form can't be moved or sized while minimized or maximized A module is not a valid type A procedure of that name already exists

  14. Array function (Visual Basic for Applications)

    In this article. Returns a Variant containing an array.. Syntax. Array(arglist). The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Variant.If no arguments are specified, an array of zero length is created. Remarks. The notation used to refer to an element of an array consists of the variable name followed by ...

  15. Excel VBA Array for Beginners

    An array in VBA is a special type of variable that can store multiple values of the same data type. By using arrays, you can read and manipulate a list of data faster than if it were stored in an object such as a range or table.

  16. excel

    Sub assigningvalues () Dim i As Integer Dim myArray (20) As Variant Dim finalrow As Long ActiveSheet.Range ("A1", Range ("A1").End (xlDown)).RemoveDuplicates Columns:=Array (1) finalrow = ActiveSheet.Cells (ActiveSheet.Rows.Count, "A").End (xlDown).Row 'For i = 2 To finalrow -> I get overflow error when I use this range For i = 2 To Cells (2...

  17. vba

    1 I have a dictionary and which also storing array. Here is the code and I am trying to assign some value to the array. But it always fails to assign value to the array. How can I solve this? Thanks Code:

  18. Excel VBA Multidimensional Array for Assigning Values (6 Ways)

    Excel VBA Multidimensional Array for Assigning Values: 6 Suitable Examples 1. Populating Excel Sheet by Assigning Values Directly Inside Code 2. Assigning Values to Array from One Sheet to Another 3. Applying "For" Loops to Assign and Display Multidimensional Array Values 3.1.

  19. How to Fix 'VBA Can't Assign to Array' Issue in 3 Minutes (Excel)

    When you're assigning values to an array in VBA, you need to do it one at a time, using the array's index. If you're trying to assign a value to an array without specifying an index, or if you're trying to assign a set of values to an array all at once, this could be causing the error.