An Early Exit

Sometimes, depending on the data, you may want to terminate an event or other kind of procedure early. You can combine the If and Exit statement to do just that.

The Exit statement has the following format:

Exit Sub | Function | Do | For

The vertical bars between the keywords indicate that only one of those keywords can follow Exit; the one you use depends on what you want to exit from. To exit from an event procedure, which is a subroutine as you learned in Day 4, "Creating Menus," you use the Exit Sub statement. To exit from a function procedure, you use the Exit Function. The Exit Do and Exit For statements will become clear before today's lesson is finished.

Listing 6.4 terminates the event procedure in line 3 if the If statement's condition is true.

Listing 6.4. Use an Exit Sub to terminate a procedure early.

1:  Private Sub cmdCalc ()
2:     If (txtSales.Text < 5000.00) Then
3:       Exit Sub   ' Terminate procedure
4:     Else
5:       ' If the bonus is at least $5,000...
6:       ' perform the next statement that
7:       ' displays the bonus as a percentage
8:       ' of the sales
9:       lblBonus.Caption = txtSales.Text * .05
10:    End If
11: End Sub
 
Top Home