Vba Arrays - Excel Off The Grid
Vba Arrays - Excel Off The Grid
AWARDS
Get our FREE VBA eBook of the 30 most useful Excel VBA macros.
Microsoft MVP:
Automate Excel so that you can save time and stop doing the jobs a trained monkey could
do.
WHERE TO FIND ME
YouTube:
YouTube
Twitter:
Follow @exceloffthegrid
BOOKS
Tell me more…
RECENT POSTS
Before I start, let me share a little secret with you… I really dislike VBA arrays. There just seem to be too many
oddities in how they work. Compared with other programming languages, VBA seems to make arrays overly How to FILTER by a list in Excel
complicated. If you feel the same, then you’re in the right place. This post contains a lot of code examples, (including multiple lists)
which will cover most of your use cases.
Excel number formats for accounting &
finance you NEED to know
Thank you to Jon Peltier for suggesting how I can improve this post.
I recommend you download the example file for this post. Then you’ll be able to work along with examples and
How to run Excel macros from Power
see the solution in action, plus the file will be useful for future reference.
Automate Desktop
Contents
1. What is an array & when to use it?
2. Static vs. dynamic Arrays
2.1. Declaring an array as a variable
2.2. Create a static array
2.3. Create a static two-dimension array
2.4. Create a dynamic array
3. Index locations
3.1. Index of the first element
3.2. Index of the last element
4. Assigning values to an array
4.1. Assign values to elements individually
4.2. Assign values to elements with an array list
4.3. Assign values to elements with a string
4.4. Assign values to elements from a range
5. Convert arrays to string and ranges
5.1. Convert array to string
5.2. Convert array to range
6. Looping through each element in an array
6.1. For loop: single-dimension array
6.2. For loop: multi-dimension array
6.3. For Each loop: single-dimension array
6.4. For Each loop: multi-dimension array
7. Check if a value is in an array
8. Find the index of an element in an array
9. Resizing an array
9.1. Resize and blank values
9.2. Resize array and keep existing values
10. Sorting array order
11. Reverse array order
12. Filter an array
13. Conclusion
Let’s assume we have a list of 5 suppliers that can change each month. Look at the screenshot below as an
example:
To hold the supplier list, we could create 5 variables, then assign values from a worksheet to each variable.
This is what the code might look like:
Sub ListSuppliers()
End Sub
That doesn’t seem too bad, does it? Now imagine we have to list 1,000 suppliers, or 10,000 suppliers; that’s
going to be a very dull day of coding. Unless, of course, we use an array.
Also, what if we have an unknown number of suppliers. What are we going to do then? We would need create
more variables than we need just to ensure there is enough space. Again we can turn to a VBA array.
Look at the code below; it creates an array to hold 10,000 suppliers, populated from 10,000 cells in column A.
You don’t need to understand it at this stage; instead, just be impressed with how neat and tidy it is. It’s
difficult to believe that a VBA array containing a list of 10,000 items takes less code than a list of five variables.
Sub ListSuppliersArray()
Next i
End Sub
Using the VBA above, it doesn’t matter if there are 1, 20, 50, 1,000, or 10,000 items, the code will be the same
length. This is the advantage of arrays; we don’t have to write the same code over and over. Instead we can
write one piece of code which add all of the items into an array.
But, it doesn’t end there. If the values to assign are in a contiguous range, we can reduce the code to just a few
lines. Look at the macro below; a range of 10,000 cells is assigned to a Variant variable type, which
automatically creates an array of 10,000 items (no looping required). Amazing stuff, right?
Sub ListSuppliersArray()
Suppliers = ActiveSheet.Range("A2:A10001").Value2
End Sub
OK, now we understand the benefits of VBA arrays, let’s learn how to use them.
The difference between the two is how they are created. After that, accessing values, looping through
elements and other actions are exactly the same.
Arrays, like other variables can be any variable type. Integers, strings, objects and ranges, etc., can all be
included in an array.
A variable declared as a Variant can hold any data type. Interestingly, a Variant type can also become an array
if we assign an array to it.
Look at the code below. First, a standard variable with a Variant data type is created, then an array is assigned
to the variable. As a result, the variable has become an array, and can be treated the same as other arrays.
End Sub
By default, arrays have base 0, which means they start counting at 0, rather than 1. The following macro
creates a static array with 6 elements (0, 1, 2, 3, 4, 5). Notice that the array is created with 5 inside the
parentheses, but because of base 0, there are actually 6 elements created.
Sub CreateStaticArrayStartingAtZero()
End Sub
We can turn arrays into base 1 (i.e., counting starts at 1) by inserting the following code at the top of the code
module.
Option Base 1
Sub Create2DimensionStaticArray()
arr(1, 1) = "Alpha"
arr(1, 2) = "Apple"
arr(1, 3) = "Ant"
arr(2, 1) = "Bravo"
arr(2, 2) = "Ball"
arr(2, 3) = "Bat"
arr(1, 1) = "Charlie"
arr(2, 2) = "Can"
arr(3, 3) = "Cat"
End Sub
We’re not limited to just two dimensions, VBA allows us up to 60! I don’t think I’ve very used more than 3, but
it’s good to know that there are so many spare.
NOTE – The term “dynamic array” in Excel and VBA is not the same; they are entirely different
methodologies.
The following macro initially creates a dynamic array with no size. Then, later in the macro, the array is resized,
using ReDim, to create 5 elements, starting at 1.
Sub CreateDynamicArray()
End Sub
A dynamic array can be resized many times during macro execution (we will see this later in this post).
Index locations
Each element of an array has an index number (i.e., the position in the array).
Sub GetIndexOfFirstElement()
End Sub
Sub GetIndexOfLastElement()
'Create the array
Dim arr As Variant
arr = Array("Alpha", "Bravo", "Charlie")
End Sub
Sub AssignFixedValuesToArray()
arr(1) = "Alpha"
arr(2) = "Bravo"
arr(3) = "Charlie"
arr(4) = "Delta"
arr(5) = "Echo"
End Sub
Sub AssignValuesFromListToArray()
End Sub
Sub SplitStringIntoArray()
End Sub
Sub ReadRangeToArray()
End Sub
When using this method, the created array will always contain two-dimensions (just like the rows and column
from the range). So, even if the source range is a single row or column, the array will still contain two-
dimensions.
Sub JoinArrayIntoString()
'Create an array
arr = Array("Alpha", "Bravo", "Charlie")
End Sub
Sub WriteArrayToRange()
Dim arr As Variant
arr = Array("Alpha", "Bravo", "Charlie", "Delta", "Echo")
End Sub
For loop – Using the LBound and UBound functions to determine the number of times to loop
For Each loop – Loops through every item in the array
NOTE – The For Each loop can only read the elements in an array; it cannot be used to change the
values assigned to elements.
Sub ForLoopThroughArray()
MsgBox arr(i)
Next i
End Sub
Sub ForLoopThrough2DimensionArray()
arr(1, 1) = "Alpha"
arr(1, 2) = "Apple"
arr(1, 3) = "Ant"
arr(2, 1) = "Bravo"
arr(2, 2) = "Ball"
arr(2, 3) = "Bat"
arr(3, 1) = "Charlie"
arr(3, 2) = "Can"
arr(3, 3) = "Cat"
MsgBox arr(i, j)
Next j
Next i
End Sub
Sub ForEachLoopThroughArray()
MsgBox arrElement
Next arrElement
End Sub
Sub ForEachLoopThrough2DimensionArray()
MsgBox arrElement
Next arrElement
End Sub
The function takes two arguments (1) the array and (2) the value to find.
Next arrElement
IsValueInArray = False
End Function
The following is an example of how to call the function above; it tells the function to search for the string
“Bravo” within the array. The result returned is True if found, or False if not.
Sub UseFunctionValueInArray()
End Sub
The function takes two arguments the value to find and the array to search.
Dim i As Long
PositionInArray = i
Exit Function
End If
Next i
PositionInArray = False
End Function
The following shows how to use the function above; if the string “Bravo” is found within the array, it will return
the index position, or False if not found.
Sub UseFunctionPositionInArray()
End Sub
Resizing an array
As we’ve seen above, dynamic arrays are declared without a size. Then later in the code, ReDim is used to size
the array. ReDim can be used many times during the macro to resize a dynamic array.
When resizing an array with ReDim, the assigned values will be cleared out. To keep the existing values we
must use the ReDim Preserve command.
Sub ResizeArraySize()
'Loop through array using For Each method - all elements blank
For Each arrElement In arr
MsgBox arrElement
Next arrElement
End Sub
Sub ResizeArraySizeKeepValues()
'Loop through array using For Each method - all elements blank
For Each arrElement In arr
MsgBox arrElement
Next arrElement
End Sub
Dim i As Long
Dim j As Long
Dim temp As Variant
For j = i + 1 To UBound(arr)
temp = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next j
Next i
SortingArrayBubbleSort = arr
End Function
arr = SortingArrayBubbleSort(arr)
End Sub
arrSize = UBound(arr)
arrMid = (UBound(arr) - LBound(arr)) \ 2 + LBound(arr)
temp = arr(arrSize)
arr(arrSize) = arr(i)
arr(i) = temp
arrSize = arrSize - 1
Next i
ReverseArray = arr
End Function
Sub CallReverseArray()
arr = ReverseArray(arr)
End Sub
Filter an array
Along with LBound, UBound, Split and Join, another useful built-in function is Filter.
The Filter function returns an array that includes only the elements which contain a sub-string. In the example
below the filteredArr array only includes the elements which contain the letter “o”,
Sub FilterArray()
MsgBox arrElement
Next arrElement
End Sub
Conclusion
Hopefully, this post covers most of your needs. However, VBA arrays are a vast topic, so make use of online
forums to ask specific questions which this post doesn’t answer.
My parents tell me that at the age of 7 I declared I was going to become a qualified
accountant. I was either psychic or had no imagination, as that is exactly what
happened. However, it wasn't until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children
during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a
small number of simple tools, I could combine them together in different ways to automate nearly all my
regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to
other professionals in our training program so they too can spend less time at work (and more time with their
children and doing the things they love).
I'm guessing the examples in this post don't exactly match your situation. We all use Excel differently, so it's
impossible to write a post that will meet everybody's needs. By taking the time to understand the techniques
and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by
discovering your own solutions.
2. Ask the 'Excel Ninja' in your office. It's amazing what things other people know.
3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people
on these forums are generally giving their time for free. So take care to craft your question, make sure
it's clear and concise. List all the things you've tried, and provide screenshots, code segments and
example workbooks.
4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel
problems.
What next?
Don't go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
How to FILTER by a list in Excel number formats for How to expand columns How to run Excel macros
Excel (including multiple accounting & finance you dynamically in Power from Power Automate
lists) NEED to know Query Desktop
How To Create Sheets For Power Query: Get data How to create QR codes in Move data between
Each Item In PivotTable when sheet/Table names Excel for FREE (3 easy workbooks (Power
Field change (2 ways) ways) Automate+Office Scripts)
How to filter by a list in How to run any macro from How to get data from Automatic commentary
Power Query (4 methods) one button (magic macro) SharePoint List with Power writing formula in Excel –
Query Amazing LAMBDA
← Dynamic arrays and VBA user defined functions Power Query – Absolute and relative references →
(UDFs)
Leave a Reply
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Website
Post Comment
Theme by Out the Box Home Blog Newsletter Books Training Academy About Terms and conditions Privacy policy Affiliate disclosure Contact