| Posted at 05:04 AM on December 29, 2008 |
Previously, we saw that you can drive yourself loopy, and repeat instructions over and over again, a time saver once you get it right. But what if you want to stop the loop early because something has happened?
These are called conditional loops. Easy real world definition:
Going with your girl, stopping because you have an argument, getting back together again, another argumental split and so on.
Expanding a bit on the PutAppleInBox subroutine, we can add an IF….THEN…..ENDIF clause (not Santa). We do this to get the routine to “jump” over a few numbers, once a certain number or condition has been reached (my age went from 15 to 18 every Friday night so I could go to the pub):
Sub PutAppleInBox()
Dim intRepeatThisLoop As Integer
Dim intBoxOfApples As Integer
For intRepeatThisLoop = 1 To 10
If intBoxOfApples = 8 Then
intBoxOfApples = 10
End If
intBoxOfApples = intBoxOfApples + 1
Next
MsgBox ("There are " & intBoxOfApples & " apples in the box")
End Sub
Using the code (above), once intBoxOfApples reaches 8, the code makes intBoxOfApples = 10 and completely misses out 9. This ends the For loop early.
There are many uses of If:
Categories: VBA Tutorials (mixed nuts)