Developer Documentation Library > Scripting > mrScriptBasic overview > mrScriptBasic language reference > Statements > If...Then...Else
 
If...Then...Else
An If...Then...Else structure conditionally executes a group of statements, depending on the value of an expression.
Block syntax
If expression Then
[statements]
[ElseIf expression-n Then
[elseifstatements]] ...
[Else [elsestatements]]
End If
Single-line syntax
If expression Then statements [Else elsestatements]
Arguments
expression
Any expression that can be evaluated to return a result. The result will be coerced to True or False.
statements
One or more statements that are executed if expression evaluates to True.
expression-n
Same as expression.
elseifstatements
One or more statements that are executed if expression-n evaluates to True and no previous expression or expression-n has evaluated to True.
elsestatements
One or more statements executed if no previous expression or expression-n has evaluated to True.
Remarks
You can use the single-line syntax for short, simple tests. However, the block syntax provides more structure and flexibility and is usually easier to read, maintain, and debug.
When executing the block syntax, expression is tested. If the expression evaluates to True, the statements following Then are executed. If expression evaluates to False, each ElseIf (if any) is evaluated in turn. When a True condition is found, the statements following the associated Then are executed. If none of the ElseIf statements are True (or there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.
The Else and ElseIf clauses are both optional. There can be as many ElseIf statements as required after the If, but none can appear after the Else clause. If statements can also be nested.
Examples
The following data cleaning examples illustrate using If...Then...Else statements.
Simple If statement
If age < 20 Then
age = 20
End If
One-line If statement
If age < 20 Then age = 20
If statement with an Else
If age < 0 Then
Job.DropCurrentCase()
Else
AgeCheck()
End If
If statement with a nested If, ElseIf, and Else
If age < 0 Then
Job.DropCurrentCase()
Else
AgeCheck()
If gender = {female} Then
FemaleCheck()
ElseIf gender = {male} Then
MaleCheck()
Else
Job.DropCurrentCase()
End If
End If
An If statement with questions
If gender = {female} Then
Pregnancy.Ask()
End If
An If...Else statement with questions
If children > 0 Then
Children.Ask()
Else
NoChildren.Ask()
End If
An If statement with ElseIf, nested If, and Else with questions
If PrefDrink = {wine} Then
WinesTasted.Ask()
If WinesTasted.ContainsAny(WHITE_WINES) Then
WhiteWines.Ask()
End If
If WinesTasted.ContainsAny(RED_WINES) Then
RedWines.Ask()
End If
ElseIf PrefDrink = {beer} Then
BeersTasted.Ask()
Else
OtherPref.Ask()
End If
See also
Statements