If-Then-Else Statements
If statements are the most widely used control statements in Sax Basic. If you only learn one control statement this should be the one. In the simplest form it is very easily understood, but nested If statements can get complicated as we shall see.
The basic form of the If statements is:
If [Condition] Then
[Statements]
Else
[Statements]
End if
An example of the use of an If statement could look like this:
Sub CheckSourceListTitle()
Dim Title As String
Dim userTitle As String
Title = PSL.ActiveProject.SourceLists.Item(1).Title
userTitle = InputBox("Enter first source list name!")
If Title <> userTitle Then
MsgBox ("This is the wrong name: " & userTitle)
Else
MsgBox ("This source list name is correct.")
End If
End Sub
This example also illustrates other features of Sax Basic. The InputBox function is very useful for getting information from the user. It displays a string (some text) to the user and returns the information typed by the user. It also illustrates how to extract the title of a source list. It should be mentioned that this subroutine is not complete. Just try clicking cancel in the dialog box.
If statements can be nested. This means that you can have an If statement inside another If statement. The general form would be:
If [Condition] Then
If [Other condition] Then
[Statements]
Else
[Statements]
End If
Else
[Statements]
End if
You can nest as many If statements inside each other as you please, but it gets complicated and you might loose track of what you are doing. Generally avoid more than three or four nested If statements. You can also modify the If statements with an ElseIf. It's much harder to explain than to understand. The general form is:
If [Condition] Then
[Statements]
ElseIf [Condition] Then
[Statements]
Else
[Statements]
End if
The following example illustrates the use of the structure:
Sub Season()
Dim TodaysMonth As Integer
TodaysMonth = Month(Now)
If TodaysMonth < 3 Then
MsgBox "Winter"
ElseIf TodaysMonth < 6 Then
MsgBox "Spring"
ElseIf TodaysMonth < 9 Then
MsgBox "Summer"
ElseIf TodaysMonth < 11 Then
MsgBox "Autumn"
Else
MsgBox "Winter"
End If
End Sub
Look for other examples of If statements in this documents, and play around with the structure until you feel you are comfortable with it. As mentioned this is a very important control structure.