P. 1
Vba for Excel Made Simple

Vba for Excel Made Simple

4.85

|Views: 14,684|Likes:
Published by edumeno

More info:

Published by: edumeno on Oct 23, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

08/07/2013

pdf

text

original

The expressions on both sides of a comparison operator must conform to the
same data type or at least compatible data types. You cannot compare a string
to a numeric data type, e.g. “one” with 1. They are stored differently in the
computer, and if you try, you will get a type mismatch error. You can
compare any numeric data type against any other numeric data type most of
the time. In other words, you can test whether a single-precision value is less
than or greater than an integer value, such as 100 >99.99. Clearly, this
comparison would return the result True.

The If statements

Many of the previous examples have shown that programs often have to
make decisions. This means that a program will follow one course of action
if one comparison is true or perhaps another course of action if it is false.
There are two main structures for implementing decisions in VBA: If and
Select Case.
If uses the comparison operators you learned earlier in this lesson to test data
values, and can test whether to execute complete blocks of code. This means
that If lets your program execute only parts of the program if the data
warrants partial execution. In this section we will look at three variants of the
If statement. These are:

M

One-way selection using If…Then

M

Two-way selection using If…Then…Else

M

Multiway selection using If…Then……ElseIf…Else

The one-way If structure: If…Then

The one-way If structure is used in programs when some course of action is
taken if the outcome of a decision is true; otherwise, no alternative action is
taken when the decision is false. It has the following syntax:

If ComparisonTest Then
one or more VBA statements

End If

The End If statement lets VBA know where the body of the If structure ends.

117

Suppose we wanted to write a macro that prompts the user with an InputBox
to enter a range of cells, which it will then highlight. The program is
implemented in Listing 6.1. It uses a one-way If…Then statement, that
checks to see if that the range variable Rng is not empty. If it is not, then the
range is selected using the Rng.Select statement.

Listing 6.1

'Highlights selected user range
Sub GetRange()
Dim Rng As Range
Set Rng = Application.InputBox (prompt: = "Enter range", Type: =8)
If Not (Rng Is Nothing) Then
Rng.Select

End If
End Sub

Figure 6.1 Screenshot from Listing 6.1

Tip

Be careful when you compare non-integers for equality. Decimal numbers are difficult to represent

internally. For example, if you assigned 10.2342 to a single-precision variable and assigned 10.2342 to

a double-precision variable, VBA might return false if you compare the values for equality. Internally, one

of the variables might actually hold 10.32420001 because of rounding errors when storing significant

figures. You can safely compare two currency values for equality, however, because VBA compares their

accuracy to two decimal places.

118

Figure 6.2 The error message from Listing 6.2

The two-way If

The one-way If statement is applied when you want the program to execute
one set of instructions if some condition is true, otherwise do nothing.
However, you may want the program to execute one set of instructions if
some condition is true, else execute another set of instructions. This type of
logical construct is called a two way if statement. The general syntax is:

If ComparisonTest Then
One or more VBA statements

Else

One or more VBA statements

End If

We can see that whereas If executes code based on the comparison test’s true
result, the Else statement executes code based on the comparison test’s false
result. Else is an optional part of the If statement and specifies the code that
executes if the comparison test is false.
If we look at the previous example, we can see that there is a problem. If a
valid range is selected then the range is highlighted, if not, then nothing
happens. However, in this event, we might want to prompt the user to enter
a valid range, perhaps using a MsgBox. A two-way If structure has been used
to implement this change in Listing 6.2. Note that the comparison test is the
same, but an Else alternative displays the error message (see Figure 6.2).

Listing 6.2

'Highlights selected user range
Sub GetRange ()
Dim Rng As Range
Set Rng = Application.InputBox (prompt: ="Enter range", Type: =8)
If Not (Rng Is Nothing) Then
Rng.Select

Else

MsgBox "Please choose a valid range"

End If
End Sub

Indentation helps to
identify the code inside
the If statement's body

119

Figure 6.3 Screenshot from Listing 6.3

This next example shows how the two-way If can be used. This macro will
input a person’s sex and display the message “You can retire at 60” if the sex
of the person is female, otherwise display the message “You can retire at the
age of 65”. It uses a string variable to store the sex of the person, which is
input through an InputBox command. The two-way If then checks if the sex
is female and outputs the corresponding message. Otherwise, it displays the
alternative message.

Listing 6.3 Another two-way If example

Sub retireAge ()
Dim sex As String
sex = InputBox ("Input the sex of the person", "Person's Sex")
If (sex="female")
Then MsgBox "You can retire at the age of 60"

Else

MsgBox "You can retire at 65"

End Sub

Parentheses are not
required around the test
but they help separate it
from the rest of the code

120

Self-assessment exercise

What is wrong with this If statement?

If (z > 0) Then
MsgBox "This"

Else

MsgBox "That"
End Else

The multi-way If statement

The two-way If statement is applied when you want the program code to
execute one set of instructions if some condition is true, else execute another
set of instructions. However, there are times when you may want to execute
one set of instructions if some condition is true, or else if some other
condition is true, you may want to execute another set of instructions, and
so on, until all alternatives have been completed. The general syntax is:

If ComparisonTest Then
One or more VBA statements

Else If

One or more VBA statements

Else If

One or more VBA statements

Else

One or more VBA statements

End If

Consider the previous example. This was written as a two-way If, where the
first condition checked if the person’s sex was female and displayed the
appropriate message, else the alternative message for a male person would
be displayed. The problem is that the program would take any alternative
value other than female. We will extend this two-way If to a three-way If so
that first condition will check if the person’s sex is female and display the
appropriate message, else if the person’s sex is male, it will display the male
message, else it will display an error message such as “You have entered an
invalid sex”. In Listing 6.4, the If checks if the sex is female and display the
corresponding message. Else If checks if the sex is male, will display the
corresponding, and the final Else will display an error message.

121

Listing 6.4

Sub retire_age ()
Dim sex As String
Sex = InputBox ("Input the sex of the person (male or female)", "Person's Sex")
If (sex="female") Then
MsgBox "You can retire at the age of 60"
Else If (sex = "male") Then
MsgBox "You can retire at 65"

Else

MsgBox " Error! You have entered an invalid sex."

End If
End Sub

Take note

There is a single-line form of the If statement, with this format:

If ComparisonTest Then VBStatement(s)

For example,

If (sex=”female”) Then MsgBox “You can retire at the age of 60”

This does not require an End If statement because the comparison test

and the body of the If reside on the same line.

Figure 6.4 Screenshot of Listing 6.4

122

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->