Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 7 Using Loops and Timers 191



  1. When you’re finished, click the Close button on the form to stop the program.


As you can see, this solution is a little more elegant than the previous example because
the user can click just one button, not a form button and a message box button. The
shortcoming of the interface in the first program wasn’t the fault of the For... Next loop,
however, but rather the limitation I imposed that the Button1_Click event procedure use
only local variables (in other words, variables that were declared within the event procedure
itself). Between button clicks, these local variables lost their value, and the only way I could
increment the counter was to build a loop. By using an Integer variable with a greater
scope, I can preserve the value of the Counter variable between clicks and use that numeric
information to display files within the Button1_Click event procedure.

The Exit For Statement
Most For... Next loops run to completion without incident, but now and then you’ll
find it useful to end the computation of a For... Next loop if a particular “exit condition”
occurs. Visual Basic allows for this possibility by providing the Exit For statement, which
you can use to terminate the execution of a For... Next loop early and move execution
to the first statement after the loop.

For example, the following For... Next loop prompts the user for 10 names and
displays them one by one in a text box unless the user enters the word “Done”:
Dim i As Integer
Dim InpName As String
For i = 1 To 10
InpName = InputBox("Enter your name or type Done to quit.")
If InpName = "Done" Then Exit For
TextBox1.Text = InpName
Next i
If the user does enter “Done,” the Exit For statement terminates the loop, and execution
picks up with the statement after Next.
Free download pdf