The final line of code shows whatever
TestText
contains. Unless you select
Hello
or the end of the line, the message box contains the selected text. Try
out the example code by using various selections,
or set the cursor at the
end of the line, and you can see the usefulness of this feature.
Using the If...Then...Else statement
The
If...Then...Else
statement makes one of two choices. If the expres-
sion controlling the statement is true, VBA executes
the first set of state-
ments. On the other hand, if the expression is false, VBA executes the second
set of statements.
The example in this section determines whether two numbers are equal or
whether one is greater than the other.
To test the
If...Then...Else
state-
ment, create a new Excel worksheet. The code relies on input from the work-
sheet for test purposes. Figure 5-1 shows the setup and some sample input.
The code used for this example makes three checks: equal to, greater than,
and less than.
Listing 5-2 shows the code that you need in order to make
these three checks. (You can find the source
code for this example on the
Dummies.com site at
http://www.dummies.com/go/vbafd5e
.)
Figure 5-1:
Use this
worksheet
to compare
the value
of two
numbers.
115
Chapter 5: Creating Structured Programs
10_046500 ch05.qxp 12/5/06 5:35 PM Page 115
Listing 5-2
Using the If...Then...Else Statement for Comparisons
Public Sub CompareNumbers()
‘ Create variables to hold the two numbers.
Dim Input1
As Double
Dim Input2 As Double
‘ Create an output string.
Dim Output As String
‘ Fill the variables with input from the worksheet.
Input1 = Sheet1.Cells(3, 2)
Input2 = Sheet1.Cells(4, 2)
‘ Determine if the first number is greater than or
‘ equal to the second number.
If Input1 >= Input2 Then
‘ Determine if they are equal.
If Input1 = Input2 Then
‘ Tell the user they are equal.
Output = “The values are equal.”
Else
‘ The first number must be greater than the
‘ second.
Output = “First Number is greater than “ + _
“Second Number.”
End If
Else
‘ The first number is less than the second.
Output = “First
Number is less than Second
Number.”
End If
‘ Place the output on the worksheet.
Sheet1.Cells(6, 2) = Output
End Sub
The code begins by getting the contents of the two input cells from the work-
sheet. Always use a
Double
data type when you don’t know what kind of
number that you
might type into a worksheet, because this data type is more
flexible than an
Integer
. The first number for the
Cells
property is always
the row, and the second is the column. Although
the worksheet uses letters
for the columns, you must use numbers.
116
Do'stlaringiz bilan baham: