Excel VBA Programming - Arrays and Loops
Excel VBA Programming - Arrays and Loops
Excel VBA
Programming
Arrays and Loops
Arrays are usually used with loops. This is because it's (fairly) easy
to access each array position in a loop you just use the loop
variable between the round brackets of the array.
To test this out, set up another Sub in the coding window you
created for the last lesson. Call it ArrayExercise_2. Now type the
following code for your new Sub
https://www.homeandlearn.org/arrays_and_loops.html 1/5
21/03/2021 Excel VBA Programming Arrays and Loops
The next 5 lines store the values 10 to 50 into each position in the
array.
For i = 1 To UBound(MyArray)
https://www.homeandlearn.org/arrays_and_loops.html 2/5
21/03/2021 Excel VBA Programming Arrays and Loops
UBound(MyArray)
The UBound part is short for Upper Boundary. This gets you the
highest number in your array (there's also an LBound to get the
lowest value). In between the round brackets of UBound you type
the name of your array. Notice that you don't need round brackets
for your array name here.
The loop, then, goes from 1 to the highest value in the array, which
is 5 in this case. So we're looping round 5 times.
The thing to bear in mind here is that the value of i will change each
time round the loop. By typing the loop variable between the round
brackets of not only Cells but MyArray you can access each row or
column on the spreadsheet and each position in the array. This is a
very powerful technique and one we highly recommend you learn.
The first time round the loop, the values will really be these:
https://www.homeandlearn.org/arrays_and_loops.html 3/5
21/03/2021 Excel VBA Programming Arrays and Loops
And so on.
Test your code out. Run your Sub and then have a look at your
spreadsheet. You should see this:
The code has placed each value from the array into a cell on the
spreadsheet.
Lots more free online courses here on our main Home and Learn
site
https://www.homeandlearn.org/arrays_and_loops.html 4/5
21/03/2021 Excel VBA Programming Arrays and Loops
https://www.homeandlearn.org/arrays_and_loops.html 5/5