Title: Objectives
1Objectives
- Use block Ifs to control the flow of logic.
- Understand and use nested Ifs.
- Read and Create flowcharts indicating the logic
in a selection process. - Evaluate conditions using the relational
operators. - Combine conditions using And and Or.
- Test the Value property of option buttons and
check boxes. - Perform validation on numeric fields.
- Call event procedures from other procedures.
- Create message boxes to display error conditions.
- Apply the message box constants.
- Debug projects using breakpoints, stepping
program execution, and displaying intermediate
results.
2If Statement
- Allows for an alternative path of execution to be
carried out, depending on the outcome of a
condition. - If...Then...ElseIf condition Then
if_statement(s)Else else_statement(s)End If - The if_statement(s) are executed when the
condition evaluates to True.The else_statements
are executed when the condition evaluates to
False.
3If Statement (Continued)
- A Flow chart is sometimes used to graphically
express the flow of control.
4If Statement (Continued)
If x lt 10 Then lblMsg.Caption "OK"Else
lblMsg.Caption "No"End If
5If Statement (Continued)
If x lt 10 Then lblMsg.Caption "OK"End If
6If Statement (Continued)
- If...Then...ElseIf...Then...ElseIf condition1
Then if_statement(s)ElseIf condition2 Then
elseIf_statement(s)Else else_statementsEnd
If - The if_statement(s) are executed when condition1
evaluates to True.The elseIf_statements are
executed when condition2 evaluates to True.The
else_statements are executed when both conditions
evaluate to False.
7If Statement (Continued)
If x lt 10 Then lblMsg.Caption "OK"ElseIf x
gt 10 Then lblMsg.Caption "No"Else
lblMsg.Caption "Yes"End If
8Relational Operators
- You may use any of the following relational
operators to form the condition in an If
statement. Each evaluates to True or False. - gt greater than x gt 10
- lt less than x lt 10
- equal to txtName.Text "Jane"
- ltgt not equal to txtName.Text ltgt "Jane"
- gt greater than or equal to x gt 10
- lt less than or equal to x lt 10
- The operators are binary operators, they require
two arguments (same type), a left argument and a
right argument.
9Relational Operators (Continued)
- Numeric Relational ExamplesAssume the following
variables have been declared and assigned the
following values
intAlpha
intBravo
intCharlie
5
4
-5
intAlpha intBravo evaluates
False
intCharlie lt 0 evaluates
True
intBravo gt intAlpha evaluates
False
intCharlie lt intBravo evaluates
True
intAlpha gt 5 evaluates
True
intAlpha ltgt intCharlie evaluates
True
10Relational Operators (Continued)
- When comparing strings, each character is
compared based on its internal ASCII (American
Standard Code for Information Interchange) value.
Refer to table on page 129. - The comparison begins with the first character in
each string and continues with each successive
character. - Once two corresponding characters are found not
equal, the comparison ends and one string is
declared less than the other.
11Relational Operators (Continued)
- String Relational Examples
JOHN lt JOAN evaluates
False
HOPE lt HOPELESS evaluates
True
300ZX gt Porsche evaluates
False
Apple apple evaluates
False
Banana gt apple evaluates
False
12Relational Operators (Continued)
- Relational ExamplesAssume the following
variables have been declared and assigned the
following values
intCount1
intCount2
intCount3
txt4.Text
txt5.Text
5
5
-5
"Bit"
"Bite"
intCount1 gt intCount2 evaluates
True
intCount3 lt 0 evaluates
True
intCount3 lt intCount2 evaluates
True
intCount1 ltgt intCount2 evaluates
False
intCount1 2 gt intCount2 2 evaluates
False
txt4.Text lt txt5.Text evaluates
True
txt4.Text ltgt txt5.Text evaluates
True
txt4.Text gt "D" evaluates
False
"2" ltgt "Two" evaluates
True
"" lt "?" evaluates
True
13Boolean Expressions
- An expression that evaluates to either True or
False. - True is assigned the value -1, False the value 0.
- Every expressions that evaluates to zero (0) is
considered False, and every expression that
evaluates to non-zero is considered True. - ExampleIf blnFlag True Then ...is
equivalent toIf blnFlag Then ...
14Comparing .Text Properties
- CautionThe .Text property of a text box is a
Variant, so when compared against another text
box, VB uses string comparison.When compared to
a numeric variable or constant, VB uses numeric
comparison.
txt1.Text txt2.Text txt1.Text gt
txt2.Text
1 1
True
2 100
True
100 -100
False
0 ltblankgt
True
txt1.Text txt2.Text Val(txt1.Text) gt
Val(txt2.Text)
1 1
False
2 100
False
100 -100
True
0 ltblankgt
False
15Comparing .Text Properties (Continued)
- String comparison are case sensitive, i.e. "a" is
not the same as "A". - Use the functions UCase(string) and LCase(string)
to convert the string argument to either
uppercase or lowercase respectively. - ExamplesUCase("Hello") returns "HELLO"
- UCase("HELLO") returns "HELLO"
- LCase("HELLO") returns "hello"
- LCase("hello") returns "hello"
16Logical Operators
- Used to combine two or more relational
expressions into a compound expression. - Or (binary) num1 0 Or num2 gt 5
- And (binary) num1 0 And num2 gt 5
- Not (unary) Not num1 0
17Logical Operators (Continued)
- OrEvaluates to True if one or both conditions
are true, False otherwise. - AndEvaluates to True if both conditions are
true, False otherwise. - NotEvaluates to True if condition is false,
False if true. - Order of PrecedenceNotAndOr
18Nested If Statements
- You may have an If statement within another If
statement, either in the If part or the Else
part. - Example 1 If within the If partIf condition
Then If condition Then ' do something
End If ' do somethingElse ' do
somethingEnd If
19Nested If Statements (Continued)
- Example 2 If within the Else partIf condition
Then ' do somethingElseIf condition Then '
do somethingElse ' do somethingEnd If
20The MsgBox Statement
- Used to display informative messages to the user.
- SyntaxMsgBox Prompt, Button, Title
- Example 1 Displaying a simple messageMsgBox
"This is the prompt", vbInformation, "This is the
Title"
21The MsgBox Statement (Continued)
- Available buttons to choose from.
- vbCritical
- vbExclamation
- vbInformation
- vbQuestion
22The MsgBox Statement (Continued)
- To add a newline to the prompt, use the constant
vbCrLf. - Any text following the newline character will
appear on the next line in the message box
prompt. - Example2 Using the newline characterMsgBox
"Hello, y'all" vbCrLf "How are you?"
23Input Validation
- Question Do users always follow instructions for
inputting data? - Answer Of course not!
- Input validation deals with making sure the input
values are tested during input, rather than pop
up later as errors. - As a rule-of-thumb, the more validation you
include the better the program will be, but at
the same time, more code will be required. - The benefits do outweigh the costs, and you
should always strive to validate your input.
24Input Validation Numeric Values
- To assure a number has been entered, use VB's
IsNumeric function. - The function returns True if its argument is
numeric, else it returns False. - SyntaxIsNumeric(expression)
- Example 1 Checking numeric valuesIf
IsNumeric(txtQuantity.Text) Then intQuantity
Val(txtQuantity.Text) lblDue.Caption
curPrice intQuantityElse MsgBox "Nonnumeric
data entered",,"Invalid Data"End If
25Calling Event Procedures
- If code you need is already written in an event
procedure, you may wish to call the event
procedure rather than retyping the code. - You may call any event procedure any number of
times. - SyntaxProcedureName
- Example 1 calling an event procedure
- cmdCalculate_ClickcmdDoIt_ClickcmdDoIt_Click
26Hands-On Project
27Hands-On Project (Continued)
- Step 2 - Set the Properties
- Object Property Setting
- Form Name FBilling Caption R 'n R for
Reading 'n Refreshment - Frame1 Caption Order Information
- Frame2 Caption Coffee Selections
- Frame3 Caption ltblankgt
- option1 Name optCappuccino Caption Cappuccin
o Value True - option2 Name optEspresso Caption Espresso
- option3 Name optLatte Caption Latte
28Hands-On Project (Continued)
- Step 2 - Set the Properties (Continued)
- Object Property Setting
- option4 Name optIcedLatte Caption Iced
Latte - option5 Name optIcedCappuccino Caption Iced
Cappuccino - Label1 Caption Quantity
- Text1 Name txtQuantity Text ltblankgt
- Check1 Name chkTax Caption Takeout?
- Label2 Caption Item Amount
- Label3 Caption SubTotal
- Label4 Caption Tax (if Takeout)
29Hands-On Project (Continued)
- Step 2 - Set the Properties (Continued)
- Object Property Setting
- Label5 Caption Total Due
- Label6 Name lblItemAmount Caption ltblankgt B
orderStyle 1 - Fixed Single - Label7 Name lblSubTotal Caption ltblankgt Bor
derStyle 1 - Fixed Single - Label8 Name lblTax Caption ltblankgt BorderSt
yle 1 - Fixed Single - Label9 Name lblTotal Caption ltblankgt Border
Style 1 - Fixed Single
30Hands-On Project (Continued)
- Step 2 - Set the Properties (Continued)
- Object Property Setting
- Command1 Name cmdCalculate Caption Calculate
Selection Default True - Command2 Name cmdClear Caption Clear for
Next Item Cancel True - Command3 Name cmdNewOrder Caption New Order
- Command4 Name cmdSummary Caption Summary
- Command5 Name cmdExit Caption Exit
31Hands-On Project (Continued)
- Step 3 - Write the Code
- Declare some module-level variables and constants
-
- Private Const mcurTaxRate As Currency
0.08Private Const mcurCappuccinoPrice As
Currency 2.0Private Const mcurEspressoPrice As
Currency 2.25Private Const mcurLattePrice As
Currency 1.75Private Const mcurIcedPrice As
Currency 2.50 - Private mcurSubTotal As CurrencyPrivate
mcurTotal As CurrencyPrivate mcurGrandTotal As
CurrencyPrivate mintCustomerCount As Integer
32Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- cmdCalculate_Click()Determine price per
cup.Multiply price by quantity.Calculate tax if
needed.Calculate total subtotal tax.Display
the values.
33Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- Private Sub cmdCalculate_Click()' Calculate and
display the current amounts, add to' totals. - Dim curPrice As CurrencyDim intQuantity As
IntegerDim curTax As CurrencyDim curItemAmount
As Currency - ' Determine the current priceIf
optCappuccino.Value True Then curPrice
mcurCappuccinoPriceElseIf optEspresso.Value
True Then curPrice mcurEspressoPriceElseIf
optLatte.Value True Then curPrice
mcurLattePrice
34Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- ElseIf optIcedCappuccino.Value True Or _
optIcedLatte.Value True Then curPrice
curIcedPriceEnd If - ' calculate the item amount and update order
subtotalIf IsNumeric(txtQuantity.Text) Then
intQuantity Val(txtQuantity.Text) '
calculate item amount curItemAmount curPrice
intQuantity ' update order subtotal
mcurSubTotal mcurSubTotal curItemAmount
35Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- ' calculate the tax if a takeout If
chkTax.Value vbChecked Then curTax
mcurSubTotal mcurTaxRate End If - ' update order total mcurTotal
mcurSubTotal curTax - ' display the results lblItemAmount.Caption
FormatCurrency(curItemAmount) lblSubTotal.Capt
ion FormatCurrency(mcurSubTotal) lblTax.Caption
FormatCurrency(curTax) lblTotal.Caption
FormatCurrency(mcurTotal)
36Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- Else ' non-numeric quantity entered MsgBox
"Quantity must be numeric", vbExclamation,
"Non-numeric Entry" txtQuantity.SetFocusEnd
If - End Sub
37Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- cmdClear_Click()Clear the coffee
selections.Clear the quantity and the item
amount.Disable the takeout check box.Set the
focus to the quantity.
38Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- Private Sub cmdClear_Click()' Clear appropriate
controlsoptCappuccino.Value True - lblItemAmount.Caption vbNullString
- chkTax.Enabled False
- With txtQuantity .Text vbNumllString .SetFocu
sEnd With - End Sub
39Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- cmdExit_Click()Terminate the project
- Private Sub cmdExit_Click()
- ' terminate the projectEnd
- End Sub
40Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- cmdNewOrder_Click()Clear the previous
order.Accumulate total sales and count.Set
subtotal and total due to 0.Enable takeout check
box.
41Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- Private Sub cmdNewOrder_Click()' prepare form
for a new order' clear the item
amountscmdClear_Click - ' clear total amountslblSubTotal.Caption
vbNullStringlblTax.Caption vbNullStringlblTota
l.Caption vbNullString - ' update grand totalsIf mcurSubTotal ltgt 0
Then mcurGrandTotal mcurGrandTotal
mcurTotal mcurSubTotal 0 mcurTotal
0 mintCustomerCount mintCustomerCount 1End
If
42Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- ' enable the check boxWith chkTax .Enabled
True .Value vbUncheckedEnd With - End Sub
43Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- cmdSummary_Click()Display the average.Display
the number of Customers.
44Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- Private Sub cmdSummary_Click()' calculate the
average and display the totalsDim curAverage As
CurrencyDim strMessageString As StringDim
strFormattedAvg As String - ' do we have any customers?If mintCustomerCount
gt 0 Then ' count the last order if still
displayed, ' since it would not have been
counted. If mcurTotal ltgt 0 Then cmdNewOrder_Cli
ck End If - curAverage mcurGrandTotal / mintCustomerCount
45Hands-On Project (Continued)
- Step 3 - Write the Code (Continued)
- ' format the numbers strFormattedAvg
FormatCurrency(curAverage) - ' concatenate the message string strMessageStri
ng "Number of Orders "
mintCustomerCount vbCrLf _
"Average Sale " strFormattedAvg - MsgBox strMessageString, vbInformation,
"Coffee Sales Summary"Else MsgBox "No data to
summarize", vbExclamation, "Coffee
Sales Summary"End If - End Sub
46Debugging your Code
- The process of eradicating your bugs.
- VB offers a very nice debugger to aid us in
detecting and correcting errors in the code. - The debugger will detect run-time and logic
errors. - You can use the Immediate/Debug window to
interact with your application during debugging. - Terms to be familiar with
- step into steps into a procedure and executes
each line. - step over executes entire procedure as one
statement. - breakpoint a marked location in the code where
you would like to enter Break mode.