- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Array to Excel Range
I'm new to VBA and trying to write an array to an excel range through an array UDF.
I'm trying to output the array to a maximum number of rows that the formula was placed in. I am using the Microsoft Scripting Library for the dictionary, if that matters. With an array formula in excel (CTRL+Shift+Enter), how do I resize my array to the range that the formula was placed in and then place the array in the cells? I would like the formula on the cells to be =test("G1:J20") and the formula will be placed in the cells A1:B20.
- 1 If you ReDim an array without using Preserve then you lose the contents, but in any case you can only ReDim the last dimension of a 2-D array... Try calling your function from a test Sub to more easily debug it. – Tim Williams Jul 10, 2014 at 20:21
2 Answers 2
To read and write arrays to cells you need a 2D array. For example:
Or to just read values
Edit 1 I got rid of the evil Integer types and replaced them with Long , the native 32-bit integers in VBA.

- NOTE: Use the Range.Resize() and Range.Offset() commands to select the range of cells needed. – John Alexiou Jul 23, 2014 at 12:11
Here is a method to put an array into a worksheet range, is this what you meant?
However, since you're already looping through the dictionary for the values, why not just write the values directly to the worksheet? You can mimic the transpose by swapping your row and column indices

- Thank you so much for the reply. Is there a way to resize and place the array into a range with an array formula (CTRL+Shift+Enter)? – hollige1 Jul 10, 2014 at 22:06
- what are you resizing, how should it be resized? – Alter Jul 10, 2014 at 22:21
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged vba excel or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Largest Binary Area
- "We, who've been connected by blood to Prussia's throne and people since Düppel"
- How to calculate lattice parameter?
- Copyright issues when journal is defunct
- What sort of strategies would a medieval military use against a fantasy giant?
- Why are Suriname, Belize, and Guinea-Bissau classified as "Small Island Developing States"?
- What video game is Charlie playing in Poker Face S01E07?
- How do I align things in the following tabular environment?
- Is there a proper earth ground point in this switch box?
- remove package from CTAN
- A-Z related to countries
- Lots of pick movement
- What is a word for the arcane equivalent of a monastery? A place where magic is studied and practiced?
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- Do I need a thermal expansion tank if I already have a pressure tank?
- Are there tables of wastage rates for different fruit and veg?
- Is a PhD visitor considered as a visiting scholar?
- Bulk update symbol size units from mm to map units in rule-based symbology
- About an argument in Famine, Affluence and Morality
- Confusion About Entropy
- Recovering from a blunder I made while emailing a professor
- Has 90% of ice around Antarctica disappeared in less than a decade?
- Minimising the environmental effects of my dyson brain
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

AutoMacro: Ultimate VBA Add-in

Read all reviews
Return to VBA Code Examples
VBA Output (Print) Array to Range
In this Article
Output Data to a Different Range
Looping through an array and outputting the data, transpose array data, output to debug.print.
This tutorial will demonstrate how to output an array to a range using VBA.
Output (Print) Array to Range
Data that is stored in an array can easily be outputted into an Excel sheet . There are 3 ways to do this.
We could populate an array with data from one range in Excel , and then output the data to a different range in Excel.
The entire array is copied in one line of code to the array, and then outputted in it’s entirety to a different range of cells on the sheet.
This example will loop through an array , outputting the array to a range.
LBound and UBound returns the Starting index (Lower Bound) and Ending index (Upper Bound) of an array, in this case 1 and 10.
We can also transpose the data in the Array to the Excel sheet. Transpose allows you to display the data horizontally across the Excel sheet.
For example, if we have a list of states in Excel and wish to transpose them.

We could then run the following code:
Which would result in the following:

We can also output the array values to the debug window .
VBA Coding Made Easy

VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
(No installation required!)
Free Download

AutoMacro: VBA Add-in with Hundreds of Ready-To-Use VBA Code Examples & much more!
What is automacro.
AutoMacro is an add-in for VBA that installs directly into the Visual Basic Editor. It comes loaded with code generators, an extensive code library, the ability to create your own code library, and many other time-saving tools and utilities that add much needed functionality to the outdated VBA Editor.
Ultimate VBA Add-in
Offer expires soon!
Sale Ends Friday at Midnight
VBA (Macros) Code Examples Add-in

Introduction
Data transfer between worksheet cells and VBA variables is an expensive operation that should be kept to a minimum. You can considerably increase the performance of your Excel application by passing arrays of data to the worksheet, and vice versa, in a single operation rather than one cell at a time. If you need to do extensive calculations on data in VBA, you should transfer all the values from the worksheet to an array, do the calculations on the array, and then, possibly, write the array back to the worksheet. This keeps the number of times data is transferred between the worksheet and VBA to a minimum. It is far more efficient to transfer one array of 100 values to the worksheet than to transfer 100 items at a time.
This page shows you how to transfer data between worksheet cells and VBA ararys. You will find that with large amounts of data being transferred between the worksheet and the array, working with the array is much faster than working directly with worksheet cells.
Reading A Worksheet Range To A VBA Array
It is very simple to read a range on a worksheet and put it into an array in VBA. For example,
When you bring in data from a worksheet to a VBA array, the array is always 2 dimensional. The first dimension is the rows and the second dimension is the columns. So, in the example above, Arr is implicitly sized as Arr(1 To 5, 1 To 3) where 5 is the number of rows and 3 is the number of columns. A 2 dimensional array is created even if the worksheet data is in a single row or a single column (e.g, Arr(1 To 10, 1 To 1) ). The array into which the worksheet data is loaded always has an lower bound ( LBound ) equal to 1, regardless of what Option Base directive you may have in your module. You cannot change this behavior. For example,
Here, Arr is dimensioned automatically by VBA as Arr(1 to 10, 1 To 1) .
You can use code like the following to loop through the array of the worksheet values:
There is a special case when the range on the worksheet is a single cell. Expanding on the code above, you should use the code below if it is possible that the range is a single cell:
Writing A One Dimensional VBA Array To The Worksheet
Once you have calculated an array with the appropriate values, you can write it back to the worksheet. The array may be 1 or 2 dimensional.
To write a one dimensional array back to the worksheet, you must create a Range object, resize that range to the size of your array, and then write to the range.
Suppose we have a one dimensional array and want to write that out to the worksheet starting at cell K1 . The code must first resize the destination range. For example,
This code will write the values of Arr to range that is one row tall by UBound(Arr) columns wide, starting at range K1 . If you want the results passed to a range that is one column wide spanning several rows, use code like the following to resize the range and set the values.
NOTE that the parameters to Resize are reversed and that the array Arr is transposed before being written to the worksheet.
Writing A Two Dimensional VBA Array To The Worksheet
If you have a 2 dimensional array, you need to use Resize to resize the destination range to the proper size. The first dimension is the number of rows and the second dimension is the number of columns. The code below illustrates writing an array Arr out to the worksheet starting at cell K1 .
You can transpose the array when writing to the worksheet:
Here, the parameters to Resize are reversed and the array Arr is transposed.
Array Sizing
When you read from a worksheet to an array variable, VBA will automatically size the array to hold the range on the worksheet. You don't have to concern yourself with sizing the array. However, when writing an array from VBA to the worksheet, you must resize the destination range to hold the array. We saw this earlier in the examples. Basically, you use code like the following.
If the array being passed to the worksheet is smaller than the Range to which it is written, the unused cells get a #N/A error. If the array being passed is larger than the range to which it is written, the array is truncated on the right or bottom to fit the range.
As you've seen in the examples, passing array between the worksheet and VBA is really quite simple. Used correctly, the code snippets above can have a strong effect on increasing the performance of your VBA application.
Created By Chip Pearson at Pearson Software Consulting
This Page: cpearson.com/excel/ArraysAndRanges.aspx Last Updated: 06-May-2018 Copyright 1997 - 2014, Charles H. Pearson Site Last Updated: 10-Feb-2023
Email: [email protected] Please read this page before emailing me. Phone: (816) 325-9822 USA Central Time (-6:00 UTC) Between 9:00 AM and 7:00 PM
Essential Tools For Developers
The world's choice for creating NET-based Commercial Quality Add-Ins for Office Add-In Express Is The Most Important Tool For Creating Commerical Level Components
Learn more about Excel and VBA (Visual Basic for Applications) .
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Using arrays
- 2 minutes to read
- 7 contributors
You can declare an array to work with a set of values of the same data type . An array is a single variable with many compartments to store values, while a typical variable has only one storage compartment in which it can store only one value. Refer to the array as a whole when you want to refer to all the values it holds, or you can refer to its individual elements.
For example, to store daily expenses for each day of the year, you can declare one array variable with 365 elements, rather than declaring 365 variables. Each element in an array contains one value. The following statement declares the array variable with 365 elements. By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365.
To set the value of an individual element, you specify the element's index. The following example assigns an initial value of 20 to each element in the array.
Changing the lower bound
Use the Option Base statement at the top of a module to change the default index of the first element from 0 to 1. In the following example, the Option Base statement changes the index for the first element, and the Dim statement declares the array variable with 365 elements.
You can also explicitly set the lower bound of an array by using a To clause, as shown in the following example.
Storing Variant values in arrays
There are two ways to create arrays of Variant values. One way is to declare an array of Variant data type , as shown in the following example:
The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example.
You identify the elements in an array of Variant values by index, no matter which technique you use to create the array. For example, the following statement can be added to either of the preceding examples.
Using multidimensional arrays
In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a 2-dimensional, 5-by-10 array.
If you think of the array as a matrix, the first argument represents the rows and the second argument represents the columns.
Use nested For...Next statements to process multidimensional arrays. The following procedure fills a two-dimensional array with Single values.
- Visual Basic conceptual topics
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.
Additional resources

Excel VBA Array – The Complete Guide
by Paul Kelly | | Data Structures VBA , Most Popular | 305 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:

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)

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:

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:

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:

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.

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:

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

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

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:

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:

Sample Student data

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.)
305 Comments
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.
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
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.
Hi Richard,
It will update column A. StudentMarks(i, 1) is column A, StudentMarks(i, 2) is column B as so on.
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]
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.
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.
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
The only thing missing is how to sort multi-dimensional arrays
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
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
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
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?
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.
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.
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.
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.
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.
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.
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!
Submit a Comment Cancel reply
Your email address will not be published. Required fields are marked *

You are not logged in
You are not currently logged in.

IMAGES
VIDEO
COMMENTS
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. – Graham Monkman Nov 17, 2022 at 16:39 Add a comment Your Answer Post Your Answer
Sub test () Dim v (0 To 2, 0 To 2) As Variant Dim r As Range 'fill the array with values populate v 'range must be same dimensions as array, in this case 3x3 Set r = ActiveSheet.Range ("A1:C3") 'this simply puts array into range values r.Value2 = v End Sub Function populate (v As Variant) For i = 0 To 2 For j = 0 To 2 v (j, i) = i * j * j - i + 2 …
Sub TestArrayValuesSingle () 'Declare the array as a variant array Dim arRng () As Variant 'Declare the integer to store the number of rows Dim iRw As Integer 'Assign range to a the array variable arRng = Range ("A1:A10") 'loop through the rows - 1 to 10 For iRw = 1 To UBound (arRng) 'show the result in the immediate window Debug.Print arRng (iRw …
We could populate an array with data from one range in Excel, and then output the data to a different range in Excel. Public Sub TestOutput () 'declare the array Dim rnArray () As Variant 'populate the array with the range rnArray = Range ("A1:H24") 'output the array to a different range of cells Range ("J1:Q24") = rnArray () End Sub
It is very simple to read a range on a worksheet and put it into an array in VBA. For example, Dim Arr () As Variant ' declare an unallocated array. Arr = Range ("A1:C5") ' Arr is now an allocated array When you bring in data from a worksheet to a VBA array, the array is always 2 dimensional.
In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a 2-dimensional, 5-by-10 array. VB Dim sngMulti (1 To 5, 1 To 10) As Single If you think of the array as a matrix, the first argument represents the rows and the second argument represents the columns.
' 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 The array with values assigned
As long as the array is two-dimensional (even though you specified part of a single row, VB captured a two-dimensional array), you can just assign it to a range (of the same dimensions)... myArray = Range ("A10:D10") myArray (1, 6) = "New Value" Range ("A10:D10") = myArray