Excel VBA Programming - Arrays
Excel VBA Programming - Arrays
Home and Excel VBA
Learn
Excel VBA
Programming Arrays
So far, you have been using variables that store one piece of information. You
have stored one Integer value, one Single value, or one String. An array is a way
to store more than one value under the same name. An array looks like this
when it is declared:
If you don't want the �rst position to be 0 then you can declare it like this:
This time, the �rst position in the array is 1. The number of values it can hold
would then go from 1 to 5.
MyArray(0) = 10
MyArray(1) = 20
MyArray(2) = 30
MyArray(3) = 40
MyArray(4) = 50
So you type the name of the variable again, followed by a pair of round brackets.
Inside of the round brackets you type the number of the array position you want
to �ll. You then assign a value to that position in the normal way, after an equal
sign. In the code above, array position 0 has a value of 10, array position 1 has a
value of 20, and so on.
To get a value back out of any array, it's just like any other variable: put it on the
right of an equal sign:
ArrayValue = MyArray(1)
Notice that you still need the round brackets with a position number between
them. The line above will store whatever value is at position 1 in the array into
https://www.homeandlearn.org/excel_vba_and_arrays.html 2/4
21/03/2021 Excel VBA Programming Arrays
Let's try some arrays out. You can try these exercises in a new blank workbook,
or on a new sheet if you already have a �le opened up in Excel. If you have a
version Excel prior to Excel 2013 then just click Sheet2 at the bottom. For Excel
2013 users then you'll need to add a new Sheet. Now return to your coding
window. If you can't see the code for Sheet2, double click it in the Project
Explorer on the left: (If you can't see the Project Explorer, click View > Project
Explorer from the menu at the top.)
Create a new Sub in your code window. Call it ArrayExercise_1. Add the
following code:
Click anywhere inside of Sub and End Sub. Now press F5 to run the code. You
should see the message box display the value at position 1 in the array, which is
a value of 2. Try changing MsgBox MyArray(1) to MsgBox MyArray(4). Run the
code again and a value of 5 will appear in the message box.
Now try this. Change the message box line to MsgBox MyArray(5). Run the code
again and you'll get an error message. This one:
The Subscript is that number in round brackets. The message is telling you that
your array doesn't have that many positions.
https://www.homeandlearn.org/excel_vba_and_arrays.html 3/4
21/03/2021 Excel VBA Programming Arrays
In the next lesson, we'll take a look at how arrays and loops work together in
Excel VBA.
Lots more free online courses here on our main Home and Learn site
https://www.homeandlearn.org/excel_vba_and_arrays.html 4/4