This decision-making process uses the Bin Number column as input to a
Select Case
structure. Each clause assigns a number based on a particular
number or a range of numbers.
Listing 5-5 shows the code that you need in
order to make the choices. (You can find the source
code for this example on
the Dummies.com site at
http://www.dummies.com/go/vbafd5e
.)
Listing 5-5
Using a Select Case Statement for Multiple Decisions
Public Sub MakeChoice()
Dim CursorPosition As Integer ‘ Current row
selection.
Dim BinValue As Integer ‘
Bin for selected
row.
Dim Output As Integer ‘ Storage room number.
‘ Determine if the user has selected more than one
‘ row.
If ActiveWindow.RangeSelection.Rows.Count = 1 Then
‘ Get the cursor position.
(continued)
Figure 5-2:
Make a
choice by
using this
worksheet
and its
associated
program.
121
Chapter 5: Creating Structured Programs
10_046500 ch05.qxp 12/5/06 5:35 PM Page 121
Listing 5-5
(continued)
CursorPosition = ActiveWindow.RangeSelection.Row
Else
‘ Tell the user to select only one cell.
MsgBox “Select only one cell!”, _
vbExclamation Or vbOKOnly, _
“Selection Error”
‘ Exit the Sub without further processing.
End
End If
‘ Get the selected bin number.
BinValue = Sheet2.Cells(CursorPosition, 2)
‘ Select a choice of storage room based in the bin.
Select
Case BinValue
Case 1
Output = 1
Case 2
Output = 2
Case 3 To 4
Output = 1
Case 5 To 6
Output = 3
End Select
‘ Store the number in the worksheet.
Sheet2.Cells(CursorPosition, 3) = Output
End Sub
This example demonstrates some new techniques. The code begins by check-
ing the number of rows that you select.
If you select only one row, the code
retrieves this value by using the
ActiveWindow.RangeSelection.Row
property. You can also get hold of the column number by using the
Column
property, or the
row and column by using the
Address
property.
When you select more than one row, it’s hard for the program to know which
row to work with. The code displays an error message and then exits without
performing further
processing by using the
End
statement. This is the first
time that you’ve used
error trapping
in a program,
which means figuring out
that an error will happen before it can cause problems. See Chapter 6 for
more information on debugging and error trapping.
The next step is to retrieve the Bin Number entry by using the row informa-
tion contained in
CursorPosition
. The
BinValue
variable acts as input to
122
Do'stlaringiz bilan baham: