The IfThen Statement

The If...Then statement is used for conditional control. The syntax is:

If Condition Then

' statements go here . . . Elself AnotherCondition Then

Note that we may include more than one

ElseIf part and that both the ElseIf part(s) and the Else part are optional. We can also squeeze all parts of this statement onto a single line, which is generally only a good idea when the ElseIf and Else parts are missing. As an example, the following code deletes the current selection in the active worksheet if it contains more than one cell:

If Selection.Count > 1 Then Selection.Delete

The following example changes the color of the current selection based upon its location— selected cells in odd-numbered rows are colored red, those in even-numbered rows are colored blue:

Dim oCell As Range

For Each oCell In Selection.Cells If (oCell.Row Mod 2) = 1 Then ' odd oCell.Interior.ColorIndex = 3 ' red Else

' even oCell.Interior.ColorIndex = 5 ' blue End If Next

0 0

Post a comment