|
In our last tutorial we looked at Visual Basic statements
in the context of the VB debugger and Immediate Windows and how they help
to understand how VB statements work and debug programs. Three major VB
statement types were emphasized - assignment, conditionals, and iterations.
In this tutorial we will spend some time on the iteration or loop statements
of Visual Basic and then return to conditionals and the use of Select
Case and how it simplifies a GUI calculator application.
Loops like conditionals are the bread and butter of programming logic.
Of course, any loop can be done with conditionals like in the first column
of Table 1.
| Table 1
Comparison of Loops |
| Loop using Conditionals
|
Loop using For statement
|
Dim ii as Integer, Ival(100) as Integer, sum as Integer
' some code that reads in values to Ival
....
'Now we want to sum the values in Ival
ii=1
sum=0
Dim isw as Integer
Loopback:
sum = sum + Ival(ii)
ii=ii+1
If ii > Ubound(Ival) Then
isw = 2
Else
isw = 1
End If
On isw GoTo Loopback, Endloop
Endloop: |
Dim ii as Integer, Ival(100) as Integer,
sum as Integer
' some code that reads in values to Ival
....
'Now we want to sum the values in Ival
sum = 0
for ii = 1 to Ubound(Ival)
sum = sum i+ Ival(ii)
Next ii |
But also as can be clearly seen in Table 1, using loop statements is much
easier and less mistake prone. In the conditional Loop we have to add
an extra variable, isw, and a conditional If along with an On
.. GoTo. In contrast, the For loop is just three lines long.
Note the use of the Ubound() function - it returns the length of
the array, Ival. So the For loop just sums the values in the array
Ival.
Visual Basic provide 5 types of loop statements as shown in table 2. One
of these, the While .. Wend, has been obsoleted by the Do
loop so we will not cover it in any detail. The For Each is used
mostly for objects so it will be covered later when we discuss that topic.The
For loop, as we have just seen, is used primarily when one needs
to count through a series of values often contained in arrays. The Do
loop is used to continue a loop While a condition is true or Until
a condition is broken as shown in the examples in Table 2. The Do
loop is especially powerful in Visual Basic because it has two forms -
Do .. While/Until which guarantees at least one iteration of a
loop will be done. The second type, Do While/Until ... Loop screens
the loop condition right at the top - so maybe no iterations will be done.
Both types are useful. When reading buffers and and checking data structures
the first is often used while Do While/Until is used in error checking
like end of file and others.
Unlike the While .. Wend, the For and Do loops provide
an Exit statement. The Exit statement is important because
often a loop will have 2 or 3 conditions for exit that need to be tested
for somewhere in the body of the loop. Then a test like If xx <
xMin then Exit Do causes the loop to be immediately exited and the
next statement beyond the loop is executed next. You can see this by trying
it yourself using VB's debugger as outlined in the last tutorial.
| Table 2
Visual Basic's Iteration or Loop Statements |
| Loop type |
Examples |
Notes |
Do While/Until .. Exit Do .. Loop
Conditional 0 or more iterations loop |
Do Until cnt > 100
cnt = cnt + 1 ...
Loop |
This loop checks the condition first then proceeds
through loop if true. |
Do .. Exit Do .. Loop While/Until
Conditional 1 or more iterations loop |
Do
Input Line #fileNo, buffer
Loop While Not EOF(fileNo) |
This loop does at least one iteration then checks
if more are needed. |
For Each .. Exit For .. Next
Count through an array or collection |
For Each dVariant In dblArray
sum = sum + dVariant
Next |
The "In" group can be an array or any collection
of objects. |
For .. Exit For .. Next
Classic counting loop |
For ii= 100 To 0 Step -5
if dval(ii) > 100 Then Exit For
Next ii |
The Step value is optional and defaults to 1. The
counter variable must be numeric but not an array. |
While ... Wend
Conditional loop |
While IsNumeric(Mid(InString, ii, 1))
ii = ii + 1
Wend |
While loop has been superseded by Do While/Until -
for example, there is no Exit. |
One of the statements that Visual Basic lacks is the Continue statement.
There are times in the middle of a loop when you want to stop testing
and just go to the next iteration in the loop. One can approximate this
with nested Ifs but the logic of the nesting can quickly become quite
complicated and obscure to follow. Visual Basic does not have a Continue
statement, but its very powerful Select Case conditional statement will
fill in quite well in many cases. The best way to show how a Select Case
works is to give an example.
Select Case iswitch
Case 1 'Print a short report
itype = "short"
call PrintReport(itype)
Case 2,3,4 'Print a long, detailed report
itype="long"
call LongReport(itype,isw)
Case 5 'Graph the output
call GraphReport()
Else Case 'All other cases or values of iswitch
are an error
MsgBox iswitch + " is not expected, Error"
End Select
This statement works just about the way it reads. If the variable iswitch
equals 1, a short report is printed. If the value of iswitch is
2, 3 or 4 then a long, detailed report is to be printed. If the value
of iswitch is 5 then a graph is to be printed. And all other values
of iswitch are an error so an error message is issued with the
Else Case catching all other values. Select Case statements
can be nested in one another. This turns out to be helpful in GUI programs
where several conditions have |
| 
Figure 1 - Visual Basic Calculator |
to be tested. The calculator program shown in Figure 1 uses
a big Select Case to identify which calculator button is pressed
and then based on that info performs the requested computation.But for
some button presses we want to know which mouse button was used. A nested
Select Case is one way to handle this condition. |
There are two other type of conditional statements or better
yet functions. One is Switch() and the other is Choose().
Try these examples in VB's Immediate Window (View | Immediate Window or
CTRL+G):
i = 3
print Switch(i<0, 234,i=0, 456, i >= 2, 51, i= i,999 )
print Choose(i, -100, 0, 100) Switch() works by returning
the value immediately after the first condition that evaluates to True.In
our example, Switch() returns 51. Choose() on the hand use
the first variable as an index and returns that value - 100, in our example
above. Note that both Switch() and Choose() return Null
as their value if no condition is satisfied (Switch()) or the value
of the index variable in Choose() is less than or equal to zero
or greater than the number of choices available. In the Switch()
example, by putting in the condition i=i, 999 at the end we guarantee
that it will always return a default of 999 if none of the other conditions
are satisfied. Summary
In this tutorial we have completed the conditional statements by looking
at the versatile Select Case and with a glance at the On ..
GoTo, Switch() and Choose(). As well we have examined most
of the iteration or loop statements in fair detail. So the next tutorial
will look at Operators and Assignments to complete a three part mini-review
of basic VB grammar. After that lesson we shall return to visual programming
in Visual Basic. |
Resources:
The book Beginning VB6/Wrox covers conditional and loop statements on
pages 56-103; VB6 Black Book/Coriolis does the same on pages 104-110.
|
|