Chapter2 2024
Chapter2 2024
1
Chapter Objectives
• After completing this chapter, you will be able to:
– create programs with single alternative, dual
alternative, and multiple alternative selection
structures;
– create programs with different types of repetition
structures;
– manipulate the following controls: Frame,
OptionButton, CheckBox, SpinButton, ScrollBar, and
ListBox
2
Selection Structure
• Example 2.1. CityUDiscount.xlsm contains an
application allowing the store clerk to enter an
item's price and the quantity a customer
purchases. The application should calculate
and display the customer’s amount owed. A
10% discount will be given to the customer
when the quantity purchased is over five.
3
Selection Structure
• Example 2.1 (cont'd)
– Pseudocode for btnCalculate Click event
Calculate total amount owed = price per item * quantity
purchased
If the quantity purchased is over 5, the total amount owed after
discount = total amount owed * 0.9
Display the total amount owed (with or without discount) in
lblTotalOwe
4
Selection Structure (SS)
• Example 2.1 (cont'd)
– Flowchart for btnCalculate Click event
start
stop 5
Selection Structure
• Example 2.1a
– Modify the CityUDiscount application to apply a 5%
discount for a purchase of 5 or fewer items.
• Modified Pseudocode for btnCalculate Click event:
Calculate total amount owed = price per item * quantity purchased
If the quantity purchased is over 5, the total amount owed after
discount = total owed * 0.9
If the quantity purchased is 5 or less, the total amount owed after
discount = total owed * 0.95
Display the full amount owed after discount in lblTotalOwed
6
Selection Structure (SS)
• Example 2.1a (Cont'd)
– Modified flowchart for btnCalculate Click event
Start
Total amount owed =
price * quantity
purchased
Display total
amount owed
after discount in
lblTotalOwed
Stop 7
Selection Structure
• Visual Basic provides different structures for a single and dual
alternative selection.
– Structure 1:
If condition Then statement
– Structure 2:
If condition Then
statement block to be processed when the condition is true
End If
– Structure 3
If condition Then
statement block to be processed when the condition is true
Else
statement block to be processed when the condition is false
End If
8
Selection Structure
• The condition in the selection structure must
contain a comparison operator. Its form is
operand operator operand
• An operand can be a constant or a variable.
• An operator can be one of the following:
=, <>, >, >=, <, <=
– For examples:
If varA > 0 Then
If 0 <= VarA Then
If varA - 3 < > VarB *2 Then
If varA = "David" Then
9
Selection Structure
• Refer to Example 2.1, CityUDiscount
application with 10% discount. Partial code
for btnCalculate_Click event:
'Calculate the total amount owed
dblAmountOwed = VBA.Val(txtItemPrice.Value) * VBA.Val(txtQuantity.Value)
10
Selection Structure
• Example 2.1a (Cont’d) Refer to CityUDiscount
application with a 5% or 10% discount. Partial code for
btnCalculate Click event:
12
Selection Structure
• Example 2.2. Compare3Numbers.xlsm
contains an application that displays the
smallest and the largest of the three numbers
entered by the user. The application first
checks whether the values entered by the user
are all numeric before comparing them.
13
Selection Structure
• Example 2.2 (cont'd)
– Check the content of a TextBox control and
highlight the texts if they are non-numeric.
'Check if the first number is indeed numeric
If VBA.IsNumeric(txtNumber1.Value) = False Then
'Highlight the text in the textbox
txtNumber1.SetFocus
txtNumber1.SelStart = 0
txtNumber1.SelLength = VBA.Len(txtNumber1.Value)
End If
14
Selection Structure
• Example 2.2 (cont'd)
– Using the With / End With structure to execute a
series of statements on the same object.
'Check if the second number is indeed numeric
With txtNumber2
If VBA.IsNumeric(.Value) = False Then
'Highlight the text in the textbox
.SetFocus
.SelStart = 0
.SelLength = VBA.Len(.Value)
17
Selection Structure (Self-Study)
• Nested Selection
Structures If … Then
…
– When either a selection If …Then
18
Selection Structure
• Example 2.3. File MultipleAlt.xlsm contains an
application that displays a message based on a
letter grade entered by the user. The
application displays “Excellent” when the letter
grade is an A. When the letter grade is a B, the
application displays the message "Above
Average", and so on.
19
Selection Structure
• Example 2.3 (cont'd)
– Pseudocode of btnDisplay1_Click event:
If the letter grade is A, then it displays “Excellent”
If the letter grade is B, then it displays “Above Average”
If the letter grade is C, then it displays “Average”
If the letter grade is D or E, then it displays “Below Average”
If the letter grade is not A, not B, not C, not D, and not E, then
it displays "No Such Grade"
20
Selection Structure
• Example 2.3 (cont'd)
– Inefficient Code for btnDisplay1_Click event:
Private Sub btnDisplay1_Click()
'Display appropriate grade message
If VBA.UCase(txtGrade.Value) = "A" Then
lblGradeMessage.Caption = "Excellent"
End If
Else
lblGradeMessage.Caption = "No Such Grade"
End If
24
Selection Structure
• Example 2.4. MathematicPractice.xlsm contains an
application for practising mathematics. Users can
choose the difficulty level and the type of operation
(addition or subtraction). Assuming the user does
not know how to handle negative numbers, the
subtraction problems will not ask the user to
subtract a larger number from a smaller one, and all
involved numbers will not be negative. The
application keeps track of the number of correct
and incorrect answers the user makes. This
assessment information will only be displayed by
request.
25
Selection Structure
• Example 2.4 (Cont'd)
– The UserForm:
26
Selection Structure
• Example 2.4 (cont'd)
– Tasks for the application and the associated events:
1. Load and show the UserForm. Event: UserForm_Initialize.
2. Show a mathematical problem. Event: btnStart_Click.
3. Compare the correct answer to the user's answer. Event:
btnCheckAnswer_Click.
4. Show or hide summary report. Event: chkSummary_Click.
5. Terminate the application. Event: btnExit_Click.
27
Selection Structure
• Frame Control
– Often used to group several controls.
• Either for aesthetic appeal or programming
convenience.
– Frame control can be considered as a container
which contains other controls.
– To contain controls inside a Frame control, the
Frame control must be drawn first and then draw
other controls inside the frame or drag other
controls into the Frame.
28
Selection Structure
• Frame Control
• Example 2.5. Frame_demo.xlsm contains an
application allowing users to set the Visible or
Enable controls property in the Frame controls.
29
Selection Structure
• OptionButton Control
– Allow the user to select one option from two or more
options.
– They are often used in groups of at least two each.
– Only one OptionButton control can be selected in a group.
– Click the control to select. Once selected, one must
choose another OptionButton control in the same group
to de-select the current selected one.
– OptionButton has only two values:
• If selected, OptionButton.Value equals True.
• If unselected, OptionButton.Value equals False.
– Commonly used events include Click and Change events.
See OptionButtonDemo3.xlsm.
30
Selection Structure
• OptionButton Control
– Example 2.6a. Run UserForm NoGrouping in
optionButtonDemo1.xlsm.
31
Selection Structure
• OptionButton Control
– Example 2.6b: Run UserForm TwoGroups1 in
OptionButtonDemo1.xlsm.
• Set the GroupName property of options MS1234 and
MS5678 to Group A.
• Set the GroupName property of options MS3456 and
MS7890 to Group B.
32
Selection Structure
• OptionButton Control
– Example 2.6c: Run UserForm TwoGroups2 in
OptionButtonDemo1.xlsm.
• Put options MS1234 and MS5678 in a Frame control.
• Put options MS3456 and MS7890 in another Frame
control.
33
Selection Structure
• CheckBox Control
– Click the CheckBox control to check or uncheck.
– Unlike OptionButton control, CheckBox control is
not grouped.
– More than 1 CheckBox control can be selected.
– A CheckBox control has only two values:
• If checked, CheckBox.Value equals True.
• If unchecked, CheckBox.Value equals False.
– Commonly used events include Click and Change
events. See CheckboxDemo2.xlsm.
34
Selection Structure
• CheckBox Control
– Example 2.7: CheckboxDemo1.xlsm
35
Selection Structure
• Example 2.6d: Disable the Close button of a
Userform.
End Sub
36
Repetition Structure
• Example 2.8: SavingBalance.xlsm contains an
application that shows the amount of balance
in the savings account at the end of the year,
assuming the interest is compounded annually,
and no withdrawals or additional deposits are
made.
37
Repetition Structure
• Example 2.8 (Cont'd)
– Pseudocode of btnCalculate Click event:
Assign deposit to variable dblBalance
Assign interest rate to variable dblRate
Calculate interest = dblBalance * dblRate
Calculate new balance = dblbalance + interest
Display the amount of the new balance
• How do we modify the application to display the years
required for the savings account to reach 1 million dollars
and the account balance at that time?
38
Repetition Structure
• Example 2.8 (cont'd)
– For year 1: Original Deposit
Calculate interest = dblBalance * dblRate
Calculate new balance = dblbalance + interest
– For year 2:
Calculate interest = dblBalance * dblRate
Calculate new balance = dblbalance + interest
– For year 3:
Calculate interest = dblBalance * dblRate
Calculate new balance = dblbalance + interest
.
.
.
– Continue until new balance >= $1 million.
39
Repetition Structure
• Example 2.8 (cont'd)
– Modified the pseudocode of btnCalculate Click event to
include a repetition structure (loop):
Assign deposit to variable dblBalance
Assign interest rate to variable dblRate
Assign a 0 value to the number of years
Repeat while dblBalance < 1000000
Calculate the interest, = dblBalance * dblRate
Calculate the new dblBalance, = dblBalance + interest
Calculate the new number of years, = number of years + 1
End Repeat
Display the value of the number of years and dblBalance.
40
Repetition Structure
• Example 2.8 (cont'd)
start
– Flowchart for
btnCalculate Click
event with repetition False dblBalance
<
structure (loop): 1000000?
True
Interest = dblBalance * dblRate
Display number
of years and
dblBalance
stop
41
Repetition Structure
• Do While loop structure
– Syntax 1:
Do While loopcondition
Loop Body Statements
Loop
• The loopcondition is similar to the condition in the
selection structure.
• The loop body statements will be executed only if the
loopcondition is true.
42
Repetition Structure
• Example 2.8 (Cont'd)
– Partial code of procedure btnCalculate_Click of
ModifiedForm1 in SavingBalance.xlsm.
43
Repetition Structure
• Other Do loop structures
– Do While loop syntax 2:
Loop body statements are
Do
executed at least once and
Loop Body Statements continues to loop if the
Loop While loopcondition loopcondition is true.
– Do Until loop Syntax 1:
Do Until loopcondition Loop body statements are
Loop Body Statements executed only if the
loopcondition is false.
Loop
– Do Until loop Syntax 2:
Do Loop body statements are
Loop Body Statements executed at least once and
continues to loop if the
Loop Until loopcondition loopcondition is false.
44
Repetition Structure
• Example 2.9. SavingBalance2.xlsm contains an
application that displays the years required for
a savings account to reach 1 million dollars at
a selected interest rate and the account
balance by then.
45
Repetition Structure
• ScrollBar and SpinButton Controls
– Both allow the user to select a value by clicking on
either of two arrows, one to increase the value and
the other to decrease the value.
– Both can be displayed horizontally or vertically.
– Both have a Value property that returns an integer
value only.
– Both have no Caption property to display their values.
It is often used with a TextBox or Label control to
display its value.
– ScrollBar control is often used for selecting a value
that extends across a wide range of possible values.
46
Repetition Structure
• ScrollBar and SpinButton Controls
– Important properties include Min, Max,
SmallChange, and Value.
• Min is the smallest integer value to start with.
• Max is the largest integer value to end with.
• SmallChange: the amount of integer change at each
click on either end of the control.
• Value: existing integer value of the control.
• LargeChange for ScrollBar control: an integer value for
the amount of change when the interior of ScrollBar is
clicked once.
47
Repetition Structure
• ListBox Control
– Presents a list of items for the user to select.
– The user may select at most 1 item or multiple items
from the list if allowed.
– The items can also be displayed as checkboxes if
multiple selections are allowed or as option buttons
if only a single selection is allowed.
48
Repetition Structure
• ListBox Control
– A list can be formed by adding items to the ListBox
using the AddItem method.
– Example 2.10: Use the AddItem method to add items
to a ListBox control when the form is initialized.
49
Repetition Structure
• ListBox Control
– To allow only single item selection, set the
MultiSelect property to 0.
– To allow multiple items selection, set the
MultiSelect property to 1 or 2.
• 1 fmMultiSelectMulti – allows an item to be
selected/deselected by clicking on it, or
• 2 fmMultiSelectExtended – allows the Ctrl and Shift
keys to select multiple items.
50
Repetition Structure
• ListBox Control
– Use the Selected(index) property to return or set the
selection status of items.
• The Selected property is an array with the same number of
elements as the number of rows in the ListBox.
• Selected(i) refers to the selection status of the (i+1)th row of
the ListBox, i = 0, 1, …, number of items in the ListBox-1.
• Selected(i) = True if the (i+1)th row is selected; otherwise, it
equals False.
• Changing the Selected(index) value triggers the Change
event of the same ListBox control. The Click event of the
same ListBox control may or may not be triggered after the
Change event. See Listbox_Events.xlsm.
• The Click event is unavailable when the Multiselect property
equals 1 or 2.
51
Repetition Structure
• ListBox Control
– Example 2.11. Report the list of selected items in a message box
(Listboxexample1a.xlsm | UserFormA)
• Set the MultiSelect property to 0 for single-item selection.
• Set the MultiSelect property to 1 or 2 for multiple-item selection.
• Partial code:
'Check if the first item is selected
If ListBox1.Selected(0) = True Then
'Attach the selected item to msgSelect
msgSelect = msgSelect & ListBox1.List(0) & VBA.vbCrLf
End If Returns the text of
.
. the (0+1)th item in
. the list.
'Check if the sixth item is selected
If ListBox1.Selected(5) = True Then
'Attach the selected item to msgSelect
msgSelect = msgSelect & ListBox1.List(5) & VBA.vbCrLf
End If
52
Repetition Structure
• For loop structure
– The six If-Then structures in Example 2.11 can be
combined into a single repetition structure so that each
item in the list will be checked once iteratively. This can
be done with a For loop structure. The syntax is:
For counter = startvalue To endvalue [Step changevalue]
statements to be executed repeatedly
Next [counter]
• The counter is the counter variable (numeric) in the loop.
• The startvalue is the beginning value of the counter. It can be a numeric
constant or a numeric variable.
• The endvalue is the ending value of the counter. It can be a numeric
constant or a numeric variable.
• The changevalue is the amount of the counter changes each time through
the loop. It can be a numeric constant or a numeric variable.
– If the Step changevalue is not included, the default value of changevalue
value equals 1.
53
Repetition Structure
• For loop structure
– Each time the For statement is executed, the
counter is compared to the endvalue.
• For a positive changevalue, if counter <= endvalue,
executes the loop. Otherwise, it stops the loop.
• For a negative changevalue, , if counter >= endvalue,
executes the loop. Otherwise, it stops the loop.
– Each time the Next statement is executed, the
counter's value is incremented by changevalue.
54
Repetition Structure
• For Loop Structure
– Example 2.11 Re-visit
• Combine the six If-Then structures with a single For Loop
Structure (Listboxexample1a.xlsm | UserFormB).
• Partial code:
'Repeat for each item in the listbox control
For intItem = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(intItem) = True Then
'Attach the selected item to msgSelect
msgSelect = msgSelect & ListBox1.List(intItem) & _
VBA.vbCrLf
End If
Next intItem
55
Repetition Structure
• For loop structure
– Example 2.12. Sum up the first X integers divisible by
3, where X is specified by the user
(IntegersAccDemo1.xlsm).
Private Sub btnForward_Click()
Dim intValue As Long, intnum As Long, intAcc As Double
intValue = VBA.CLng(txtNumber.Value)
'Sum up the integers that are divsible by 3 in the range of 1 to the given
number
For intnum = 1 To intValue
If intnum Mod 3 = 0 Then intAcc = intAcc + intnum
Next intnum
57
Repetition Structure
• For loop structure
– Example 2.13: Partial Code
58
Repetition Structure
• For loop structure
– Example 2.13: Partial Code
• Returns the index of the last clicked item (selected or not) in the list.
• For single item selection: ListIndex = -1 for nothing selected.
59
• For the selection of multiple items, the smallest return value of ListIndex is 0.
Repetition Structure (Self-Study)
• For loop structure
– Example 2.9 Re-visit: Partial code
60
Repetition Structure
• ListBox control with multiple columns
– Example 2.14: A ListBox control with multiple
columns (MultiColumn.xlsm).
• To create 3 columns, in the ListBox
property window:
• Or programmatically,
ListBoxref.ColumnCount = 3
ListBoxref.ColumnWidths="30;30;30"
61
Repetition Structure
• ListBox control with multiple
columns
– To populate a ListBox with With lbxNames
.AddItem "David”
multiple columns, .List(0, 1) = "Wong”
• First, use the Additem method .List(0, 2) = "1-Jan-2018”
to add texts to column 1 of an .AddItem "Mary"
item (a row). .List(1, 1) = "Chan"
• Then, use the List(rowindex, .List(1, 2) = "12-Dec-2017”
columnindex) property to
.AddItem "John”
specify the texts of the other .List(2, 1) = "Leung"
columns in the same row. .List(2, 2) = "8-Nov-2017”
– Both rowindex and columnindex End With
start from 0.
62
Repetition Structure
• ListBox control with multiple columns
– Example 2.14 (cont’d)
• To get selected items from columns:
– First, use the Selected property to determine the selected
item in ListBox control.
– Once the selected item is determined, you can use the List
property to get or change the contents of the desired column.
63
Repetition Structure
• ListBox control with multiple columns
– Example 2.14 (Cont’d)
• Partial code of btnCheck_Click event
'Determine the selected item
With lbxNames
For intItem = 0 To .ListCount - 1
If .Selected(intItem) = True Then
'Enable fmeupdate
fmeUpdate.Enabled = True
End If
Next intItem
64
End With
Repetition Structure
• ListBox control with multiple columns
– Example 2.14 (cont’d)
• To change the value of the desired column
65
Repetition Structure (Self-Study)
• ListBox Control
– ListIndex Property
• Returns the index of the last clicked item in the ListBox.
• For a ListBox with MultiSelect property set to 0 (i.e. single
item selection), ListIndex returns the index of the selected
item for the single item selection setting. If no item is
selected, ListIndex equals -1.
• For a ListBox with MultiSelect property set to 1 or 2 (i.e.
multiple items selection), ListIndex returns the index of the
last clicked item (selected or de-selected) for the multi-
selection setting. If none of the items has been clicked,
ListIndex equals 0.
– Therefore, you cannot use ListIndex to determine whether an
item is selected by checking its value if multi-selection is enabled.
– Example: Refer to ListBoxExample8.xlsm. Try to select
and de-select items from each ListBox and check the
respective ListIndex value.
66