You can use arrays (multiple variables) in VBA to speed up code - and they are also invaluable for processing CSV files and the like.
- Arrays (this blog)
- Declaring and Using Static Arrays
- Dynamic Arrays using REDIM
- Multi-dimensional Arrays
- Splitting Text into Arrays
Posted by Andy Brown on 24 February 2012 | no comments
If you aren't already familiar with variables, make sure you read my earlier blog on creating and using variables before continuing.
What are Arrays?
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!
When to Use 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.
Arrays Starting from One, not Zero
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:
|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.