Selection
 

IF.....THEN

This statement is used to select statements based upon testing an expression.  If the expression is TRUE, certain statements can be run, whilst the expression is FALSE, different statements can be run.

Syntax Explanation
If expression Then

    statements

End If

If expression is TRUE, then statements are executed, otherwise do nothing
If expression Then

    statements1

Else

    statements2

End If

If expression is TRUE, then statements1 are executed, otherwise if expression is FALSE then execute statements2
The previous IF limited you to testing one expression.  By adding ElseIf, you can test as many expressions as you want, although a Case statement would be more efficient:
If expression1 Then

    statements1

ElseIf expression2 Then 

    statements2

Else

    statements3

End If

If expression1 is TRUE, then statements1 are executed.

If expression2 is TRUE then statements2 are executed.

If expression1 AND expression2 are FALSE then statements3 are executed

Examples
If Score >= MathsPassRate Then

    Msgbox "Student Passed Maths"

End If

If Score >= MathsPassRate Then

    Msgbox "Student Passed Maths"

Else

    Msgbox "Student Failed Maths"

End If

If Age = 18 Then

    Msgbox "Just old enough to drink alcohol"

ElseIf Age > 18 Then

    Msgbox "Old enough to drink alcohol"

Else

    Msgbox "Too young enough to drink alcohol"

End If

 


Case Statements

Case statements should be used when testing a variable which may result in more than two outcomes.

 

Syntax Explanation
Select Case variable

Case expression1

    statements1

Case expression2

    statements2

    .....

Case expressionN

    statementsN

Case Else

    statementsElse

End Select

Note:  each expression is testing the variable stated as part of Select Case...

 

If expression1 is TRUE, statements1 are executed.  All other statements are bipassed.

 

If expression2 is TRUE, statements2 are executed and so on.

 

If none of the above expressions are true, the statementsElse are executed.

 

Examples

Select Case Month

Case 1

Msgbox "January"

Case 2

Msgbox "February"

Case 3

Msgbox "March"

'etc

Case 12

Msgbox "December"

End Select

Select Case Mark

Case 0 to 39

Msgbox "Fail"

Case 40 to 59

Msgbox "Pass"

Case 60 to 100

Msgbox "Merit"

Case Else

Msgbox "You must enter a value between 0 and 100"

End Select

Non-continuous range:

Select Case Month

Case 1,3,5,7,8,10,12

Msgbox "This month has 31 days"

Case 4,6,8,11

Msgbox "This month has 30 days"

Case 2

Msgbox "This month has 28 or 29 days"

End Select

Select Case Subject

Case "English"

Msgbox "The pass mark for English is 49"

Case "Maths"

Msgbox "The pass mark for Maths is 52"

Case "Computing"

Msgbox "The pass mark for Computing is 50"

Case Else

Msgbox "You must enter English, Maths or Computing"

End Select