Finance

Charts

Statistics

Macros

Search

Single-Line If … Then … Else Statement

If condition Then statement1 [Else statement2]

Conditions are formed using comparison operators and evaluated as either True or False.

  • If the condition evaluates to True, the code following Then (statement1) is executed.
  • If the condition evaluates to False and an Else part exists, the code following Else (statement2) is executed.

The following procedure demonstrates two examples of single-line If usage. Note that the second example’s line is quite long for printing in this book, but it is still a single-line If statement:

Sub SingleLineIf()
    ThisWorkbook.Worksheets("Sheet1").Activate
    If Range("A1").Value > 100 Then MsgBox "Large"
    If Range("A1").Value < 10 Then MsgBox "Small" Else _
        MsgBox "Not small"
End Sub

Explanation:

  • In the first example, a message box appears only if the value in cell A1 is greater than 100. Otherwise, nothing happens.
  • In the second example, a message box is always displayed: it shows « Small » if the value is less than 10, otherwise it shows « Not small ».
0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx