Programming Loops in Excel VBA
Consider the following code:
Dim MyNumber As Integer
MyNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
All the code does is to add up the numbers 1 to 10. The result is then stored in the variable MyNumber
.
And that's nice an easy. But suppose you want to add up the numbers 1 to a 1000. You wouldn't have to type them all out, surely? Thankfully, you don't have to, as there's a handy programming tool at your disposal – the loop.
A loop is something that goes round and round. Programming loops go round and round until you tell then to stop. You set a starting number for your loop, and end condition, and a way to get from the starting number to the end condition. In VBA, there are four types of loop to choose from: For loops, For Each loop, Do Loops, and While loops. The first loop we'll look at is the For Loop.