Loops

A loop is when a program executes the same code again and again. Sometimes a loop runs a fixed number of times, like 100. More often, the loop runs until something happens.

Logical loops for input validation

An example. Click the button below and a program will ask you to type a number. Type anything you want. The program will keep asking until you give it a number.

Here it is in VBA:

Dim userInput As String

Do

userInput = InputBox("Please enter a number")

Loop Until IsNumeric(userInput)

Dim userInput As String

Do

userInput = InputBox("Please enter a number")

Loop While Not IsNumeric(userInput)

The general form is:

Do
[code]
Loop Until [logical expression]

Do
[code]
Loop While [logical expression]

[logical expression] is either True or False. Loop Until keeps going until[logical expression] is True. Loop While keeps going while[logical expression] is True.

[code] is often called the body of the loop. [logical expression] is often called the loop test, or just test.

Recall that [logical expression] is used in If statements as well:

If [logical expression] Then
[code]
End if

Variable changes in the loop

Remember that programming is all about the variables. A loop…

Do
[code]
Loop Until [logical expression]

… keeps going until the value of [logical expression] changes. Almost always, there's a variable in [logical expression] that's also used in [code]. That's what happened here:

Dim userInput As String

Do

userInput = InputBox("Please enter a number")

Loop Until IsNumeric(userInput)

userInput is in the body of the loop, and in the test. userInput changes in the body of the loop, depending on what the user types. Eventually, it gets a value that lets the loop terminate.

Buggy loops

Check this out:

Dim userInput As String

Dim thing as String

Do

userInput = InputBox("Please enter a number")

Loop Until IsNumeric(thing)

The variable that's in the test – thing – is not in the body of the loop. The body never changes thing. This is an infinite loop, because it will never stop. No matter what users type, thing is not affected.