Purpose
Decides which block of statements to execute (if any), based on the current value of one or more expressions.
Syntax
If if_condition Then
if_statement_list
[ ElseIf elseif_condition Then
elseif_statement_list ]
[ ElseIf ... ]
[ Else
else_statement_list ]
End If
condition is a condition which will evaluate to TRUE or FALSE.
statement_list is a list of zero or more statements.
Restrictions
You cannot issue an If...Then statement through the MapBasic window.
Description
The If...Then statement allows conditional execution of different groups of statements.
In its simplest form, the If statement does not include an ElseIf clause, nor an Else clause:
If if_condition Then
if_statement_list
End If
With this arrangement, MapBasic evaluates the if_condition at run-time. If the if_condition is TRUE, MapBasic executes the if_statement_list; otherwise, MapBasic skips the if_statement_list.
An If statement may also include the optional Else clause:
If if_condition Then
if_statement_list
Else
else_statement_list
End If
With this arrangement, MapBasic will either execute the if_statement_list (if the condition is TRUE) or the else_statement_list (if the condition is FALSE).
Additionally, an If statement may include one or more ElseIf clauses, following the If clause (and preceding the optional Else clause):
If if_condition Then
if_statement_list
ElseIf elseif_condition Then
elseif_statement_list
Else
else_statement_list
End If
With this arrangement, MapBasic tests a series of two or more conditions, continuing until either one of the conditions turns out to be TRUE or until the Else clause or the End If is reached. If the if_condition is TRUE, MapBasic will perform the if_statement_list, and then jump down to the statement which follows the End If. But if that condition is FALSE, MapBasic then evaluates the else_if_condition; if that condition is TRUE, MapBasic will execute the elseif_statement_list.
An If statement may include two or more ElseIf clauses, thus allowing you to test any number of possible conditions. However, if you are testing for one out of a large number of possible conditions, the Do Case...End Case statement is more elegant than an If statement with many ElseIf clauses.
Example
Dim today As Date
Dim today_mon, today_day, yearcount As Integer
today = CurDate() ' get current date
today_mon = Month(today) ' get the month value
today_day = Day(today) ' get the day value (1-31)
If today_mon = 1 And today_day = 1 Then
Note "Happy New Year!"
yearcount = yearcount + 1
ElseIf today_mon = 2 And today_day = 14 Then
Note "Happy Valentine's Day!"
ElseIf today_mon = 12 And today_day = 25 Then
Note "Merry Christmas!"
Else
Note "Good day."
End If
See Also:
Do Case...End Case statement