3. VbScript | If – ElseIf – Else -Then Statements

Table of Contents

Function: Option Explicit

I want to begin by talking about a function called:

Option Explicit

The Vb Programmer should add this to the very beginning or top of his script to enable the Vb Script to check itself that all the variables are defined, spelled correctly, and that you aren’t re-using them. This is valuable because if you have an error, the VbScript will tell you which line of code the error is at and…

… find variables that aren’t previously Declared. This is important because a miss-spelled variable will appear as a separate-new variable to the VbScript. But is not the variable that you may have meant to use. You can declare the variables with Dim & the variable next to it:

Option Explicit
Dim a,b,c

If – ElseIf – Else -Then Statements

Every time you open an If statement, you want to end that if with End If.

If
'Your Code here
End If

If you have more than 2 options for your If statement, then you add ElseIf for every additional option. So say you have 3 If statements. It would look like this:

If     '← First if statement
ElseIf '← 2nd if statement
ElseIf '← 3rd if statement
End If

Syntax: Note that the single quote ‘ comments out what comes after it.

For each If statement, there must be a Then after it to complete the clause.

If variable=x then
   Code Here    
ElseIf variable=c then
   Code Here
ElseIf variable=z then
   code here
End If

You also have the option of using Else instead of ElseIf at the end, if you want the last condition to trigger only if nothing else triggers.

If variable=x then
   Code Here    
ElseIf variable=c then
   Code Here
Else
   code here
End If

More on Syntax Errors:


An Else example:

Option Explicit
Dim b

b=MsgBox("Guess a Button",vbAbortRetryIgnore)

If b=vbRetry then
 msgbox "correct"
Else 
 msgbox "wrong"
End If

Output:
finito

ElseIf examples with AND & OR Functions: OR

Option Explicit
Dim b

b=MsgBox("Guess a Button",vbAbortRetryIgnore)

If b=vbRetry Or b=vbAbort then
 msgbox "correct"
Else 
 msgbox "wrong"
End If

Output:
Untitled

AND example:

Option Explicit
Dim a,z

a=MsgBox("Guess a Button",vbyesno,1)

z=MsgBox("Guess another Button",vbyesno,2)

If a=vbyes And z=vbyes then
 msgbox "correct",vbinformation
Else 
 msgbox "wrong",vbCritical
End If

Output:
yesno


What's Your Opinion?