The oneway 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.

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

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.

0 0

Post a comment