So far, we have learned to create normal conditional statements and loops. Here is an example: Sub Exercise Dim Number% Rem Request a number from the user Number% = InputBox("Enter a number that is lower than 5") Rem Find if the number is positive or 0 If Number% >= 0 Then Rem If the number is positive, display it MsgBox (Number%) End If End Sub When this procedure executes, the user is asked to provide a number. If that number is positive, a message box displays it. If the user enters a negative number, nothing happens. In a typical program, after validating a condition, you may want to take action. To do that, you can create a section of program inside the validating conditional statement. In fact, you can create a conditional statement inside of another conditional statement. This is referred to as nesting a condition. Any condition can be nested inside of another and multiple conditions can be included inside of another. Here is an example where an If...Then condition is nested inside of another If...Then statement: Sub Exercise Dim Number% Rem Request a number from the user Number% = InputBox("Enter a number that is lower than 5") Rem Find if the number is positive or 0 If Number% >= 0 Then Rem If the number is positive, accept it If Number% < 12 Then MsgBox (Number%) End If End If End Sub
The Goto statement allows a program execution to jump to another section of a procedure in which it is being used. In order to use the Goto statement, insert a name on a particular section of your procedure so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have applied to names (the name can be anything), then followed by a colon ":". Here is an example: Sub Exercise() ' Do some thing(s) here SomeLabelHere: ' Do some other thing(s) here End Sub After creating the label, you can process it. In the code before the label, you can do something. In that section, if a condition happens that calls for jumping to the label, then use a GoTo statement to send the flow to the corresponding label by typing the name of the label on the right side of GoTo. Here is an example: Sub Exercise Dim Number% Rem Request a number from the user Number% = InputBox("Enter a number that is lower than 5") Rem Find if the number is positive or 0 If Number% < 0 Then GoTo NegativeNumber Else Rem If the number is positive, display it MsgBox (Number%) End If NegativeNumber: MsgBox "You entered a negative number" End Sub In the same way, you can create as many labels as you judge them necessary in your code and refer to them when you want. The name must be unique in its scope. This means that each label must have a unique name in the same procedure. Here is an example with various labels: Sub Exercise Dim Answer As Byte Answer = InputBox(" -=- Multiple Choice Question -=-" & vbCrLf & _ "To create a constant in your code, " & _ "you can use the Constant keyword" & vbCrLf & _ "Your choice (1=True/2=False)? ") If Answer = 1 Then GoTo Wrong If Answer = 2 Then GoTo Right Wrong: MsgBox("Wrong: The keyword used to create a constant is Const") GoTo Leaving Right: MsgBox("Right: Constant is not a keyword") Leaving: End Sub Here is an example of executing the program with Answer = 1:
Here is another example of executing the same program with Answer = 2:
So far, we have learned to write a conditional statement that is true or false. You can reverse the true (or false) value of a condition by making it false (or true). To support this operation, the Visual Basic language provides an operator called Not. Its formula is: Not Expression When writing the statement, type Not followed by a logical expression. The expression can be a simple Boolean expression. Here is an example: Sub Exercise Dim IsMarried As Boolean MsgBox("Is Married: " & IsMarried) MsgBox("Is Married: " & Not IsMarried) End Sub This would produce: In this case, the Not operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was True, it would be changed to False and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it. Now consider the following program we saw in Lesson 11: Sub Exercise Dim IsMarried As Boolean Dim TaxRate As Double TaxRate = 33.0 MsgBox("Tax Rate: " & TaxRate & "%") IsMarried = True If IsMarried = True Then TaxRate = 30.65 MsgBox("Tax Rate: " & TaxRate & "%") End If End Sub This would produce: Probably the most classic way of using the Not operator consists of reversing a logical expression. To do this, you precede the logical expression with the Not operator. Here is an example: Sub Exercise Dim IsMarried As Boolean Dim TaxRate As Double TaxRate = 33.0 MsgBox("Tax Rate: " & TaxRate & "%") IsMarried = True If Not IsMarried Then TaxRate = 30.65 MsgBox("Tax Rate: " & TaxRate & "%") End If End Sub This would produce: In the same way, you can negate any logical expression.
A loop is a technique used to repeat an action. The Visual Basic language presents many variations of loops. They combine the Do and the Loop keywords. A typical loop can be used to perform an action while a condition is maintained true. To support this type of loop, the Visual Basic language provides the Do...Loop While statement. The formula of the Do... Loop While loop is: Do Statement(s) Loop While Condition
This interpreter first executes the Statement or Statements. After executing the Statement(s) section, the interpreter checks the Condition. If the Condition is true, then the interpreter returns to the Statement(s) and execute(s) it(them). The interpreter keeps doing this check-execution gymnastic. As long as the Condition is true, the Statement(s) section will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement will not be executed and the program will move on. Here is an example: Sub Exercise Dim Answer As String Do Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop While Answer <> "1" MsgBox("Wonderful, we have arrived") End Sub Here is an example of running the program:
As you may guess already, the Condition must provide a way for it to be true or to be false. Otherwise, the looping would be executed continually.
While still supporting the ability to perform an action while a condition is true, the Visual Basic language provides an alternative to the Do... Loop While we saw earlier. The other solution uses the following formula: Do Statement(s) Loop Until Condition Once again, the Statement(s) section executes first. After executing the Statement(s), the interpreter checks the Condition. If the Condition is true, the interpreter returns to the Statement(s) section to execute it. This will continue until the Condition becomes false. Once the Condition becomes false, the interpreter gets out of this loop and continues with the section under the Loop Until line. Here is an example: Sub Exercise Dim Answer As String Do Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop Until Answer = "1" MsgBox("Wonderful, we have arrived") End Sub
As mentioned above, the Do While... Loop expression executes a statement first before checking a condition that would allow it to repeat. If you want to check a condition first before executing a statement, you can use another version as Do While... Loop. Its formula is: Do While Condition Statement(s) Loop In this case, the interpreter checks the Condition first. If the Condition is true, the interpreter then executes the Statement(s) and checks the Condition again. If the Condition is false, or when the Condition becomes false, the interpreter skips the Statement(s) section and continues with the code below the Loop keyword. Here is an example: Sub Exercise Dim Number As Integer Do While Number < 46 Number = CInt(InputBox("Enter a number")) Number = Number + 1 Loop MsgBox ("Counting Stopped at: " & Number) End Sub
Instead of performing an action while a condition is true, you may want to do something until a condition becomes false. To support this, the Visual Basic language provides a loop that involves the Until keywork. The formula to use is: Do Until Condition Statement(s) Loop This loop works like the Do While... Loop expression. The interpreter examines the Condition first. If the condition is true, then it executes the Statement(s) section. Here is an example: Sub Exercise Dim Answer As String Answer = "0" Do Until Answer = "1" Answer = InputBox("Are we there yet (1=Yes/0=No)? ") Loop MsgBox("Wonderful, we have arrived") End Sub
The looping statements we reviewed above are used when you do not know or cannot anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression. One of the loop counters you can use is For...To...Next. Its formula is: For Counter = Start To End Statement(s) Next Used for counting, the expression begins counting at the Start point. Then it examines whether the current value (after starting to count) is lower than End. If that's the case, it then executes the Statement(s). Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until the value of Counter becomes equal to the End value. Once this condition is reached, the looping stops. Here is an example: Sub Exercise Dim Number As Integer For Number = 5 To 16 MsgBox(Number) Next MsgBox("Counting Stopped at: " & Number) End Sub
The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula: For Counter = Start To End Step Increment Statement(s) Next You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. Here is an example: Sub Exercise Dim Number As Integer For Number = 5 To 42 Step 4 MsgBox(Number) Next MsgBox("Counting Stopped at: " & Number) End Sub You can also set a negative value to the Increment factor, in which case the Counter will be subtracted the set value.
Since the For...Next loop is used to execute a group of statements based on the current result of the loop counting from Start to End, an alternative is to state various steps in the loop and execute a group of statements for each one of the elements in the group. This is mostly used when dealing with a collection of items. The formula is: For Each Element In Group Statement(s) Next Element The loop will execute the Statement(s) for each Element in the Group.
In the conditional statements and loops we have created so far, we assumed that the whole condition would be processed. Here is an example: Sub Exercise Dim Number As Integer For Number = 1 To 6 MsgBox(Number) Next End Sub This would produce: In some cases, you may want to exit a conditional statement or a loop before its end. To assist with with this, the Visual Basic language provides the Exit keyword. This keyword works like an operator. It can be applied to a procedure or a For loop. Consider the following procedure: Sub Exercise() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub When the procedure is called, it displays four message boxes that each shows a name. Imagine that at some point you want to ask the interpreter to stop in the middle of a procedure. To do this, in the section where you want to stop the flow of a procedure, type Exit Sub. Here is an example: Sub Exercise() MsgBox("Patricia Katts") MsgBox("Gertrude Monay") Exit Sub MsgBox("Hermine Nkolo") MsgBox("Paul Bertrand Yamaguchi") End Sub This time, when the program runs, the procedure would be accessed and would start displaying the message boxes. After displaying two, the Exit Sub would ask the interpreter to stop and get out of the procedure. Because a function is just a type of procedure that is meant to return a value, you can use the Exit keyword to get out of a function before the End Function line. To do this, in the section where you want to stop the flow of the function, type Exit Function.
You can also exit a For loop. To do this, in the section where you want to stop, type Exit For. Here is an example to stop a continuing For loop: Sub Exercise() Dim Number As Integer For Number = 1 To 12 MsgBox(Number) If Number = 4 Then Exit For End If Next End Sub When this program executes, it is supposed to display numbers from 1 to 12, but an If...Then condition states that if it gets to the point where the number is 4, it should stop. If you use an Exit For statement, the interpreter would stop the flow of For and continue with code after the Next keyword.
You can also use the Exit operator to get out of a Do loop. To do this, inside of a Do loop where you want to stop, type Exit Do.
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|