Phone (01457) 858877 or email
You can use arrays (multiple variables) in VBA to speed up code - and they are also invaluable for processing CSV files and the like.
This blog is part of our Excel VBA tutorial. We also run training courses for businesses or individuals in Microsoft Excel and in VBA programming.
If you aren't already familiar with variables, make sure you read my earlier blog on creating and using variables before continuing.
Arrays are just multi-cell variables. So whereas the following variable would hold a single value:
'a variable to hold a single name
Dim PersonName As String
the following array would hold the names of up to 6 people (by default arrays are numbered from 0):
'an array to hold the names of 6 people
Dim PersonName(5) As String
This VBA training blog shows how to create static arrays, dynamic arrays and even multi-dimensional arrays!
Be careful not to overuse arrays, particularly if you have a progamming background in other languages. Excel already comes supplied with a built-in structure for holding multiple related values:

A built-in structure for holding related information (otherwise known as a range of cells).
The main reason to use arrays is to speed up processing. For the above example, if you're going to refer to the list of 6 people frequently it may be quicker to read their names into an array and hold them in memory.
By default, arrays in VBA start from 0, but you can change this behaviour with the Option Base 1 statement:

You can not put something in the 0th element of an array if it starts at 1!
It is a difficult decision to make whether to start arrays at 0 or 1, but on balance I'd go with the default of 0 (and omit the Option Base 1 statement shown above). Here are some reasons why:
| Reason | Notes |
|---|---|
| Simplicity | If you start arrays at 0, you won't have to type Option Base 1 in every new module. |
| Consistency | VBA isn't consistent about arrays: some built-in arrays (such as the SelectedItem array returned from a file dialog box, for example) start at 1. However, on the whole most arrays start with 0. |
| Compatibility | VBA may allow you to start arrays at 1, but other languages don't. In particular, if you ever want to graduate from VBA to VB or C#, you should get used to arrays starting at 0. |
And with that out of the way, let's start looking at how to declare and use static arrays.
You can use arrays (multiple variables) in VBA to speed up code - and they are also invaluable for processing CSV files and the like.
This blog is part of our Excel VBA tutorial. We also run training courses for businesses or individuals in Microsoft Excel and in VBA programming.
Comments on this blog
This blog currently has no comments.