Visual Basic: If and Else Statements
If and else statements are the simplest way of checking if statements are true or otherwise; they are extremely useful when used in conjunction with logical and conditional operators (which are explained in the next lesson).
If statements work like so:
If CONDITION Then 'do some stuff End If
A simple if statement that checks the value of something would look like this:
If var1 = 900 Then
MsgBox("Var1 equals 900!")
End If
The "=" is a conditional operator, you will learn more about these in a few lessons as they are extremely useful with if statements.
Else statements
Else statements are always used with if statements as their contents are executed if the if statements (and/or else if statements) all fail. This is an example of a simple else statement:
If var1 = 900 Then
MsgBox("var1 = 900!")
Else
MsgBox("Im in an else statement")
End If
Elseif statements
Else if statements are always used with if statements (and usually else statements too); As you may have guessed if the if statements is false then it checks the elseif, if the elseif is true it will execute that; however if the elseif is false it will move onto the next statement (or end depending when the if ends). Here is what a simple chain of if, elseif and else statements look like:
If CONDITION Then 'Do stuff ElseIf CONDITION Then 'do different stuff ElseIf CONDITION Then 'do different stuff Else 'Do different stuff End If
Back to Visual Basic

