VBScript Tutorials - Herong's Tutorial Examples - Version 5.20, by Dr. Herong Yang

"If" Statement Examples

This section provides a tutorial example on how to use different types of 'If' statements to control code executions.

To help you understand how "If" statements work, I wrote the following the example, condition_if.html:

<html>
<body>
<!-- condition_if.html
 - Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
   ' Single-statement "If"
   bIsNewYear = True
   document.writeln("")
   If bIsNewYear Then document.writeln("Happy New Year!")

   ' Multi-statement "If"
   bIsLogOn = True
   document.writeln("")
   If bIsLogOn Then
      document.writeln("Open the log file.")
      document.writeln("Write the log message.")
      document.writeln("Close the log file.")
   End If
   
   ' "If ... Else" statement
   bIsAdmin = False
   document.writeln("")
   If bIsAdmin Then
      document.writeln("Display the delete button.")
      document.writeln("Display the edit button.")
   Else
      document.writeln("Display the view button.")
   End If
   
   ' "If ... ElseIf" statement
   iDay = 4
   If iDay = 0 Then
      sOpenHours = "closed"
   ElseIf iDay >= 1 And iDay <=5 Then
      sOpenHours = "open from 9:00am to 9:00pm"
   ElseIf iDay = 6 Then 
      sOpenHours = "open from 9:00am to 5:00pm"
   Else
      sOpenHours = "undefined"
   End If 
   document.writeln("")
   document.writeln("The library is " & sOpenHours)
</script>
</pre>
</body>
</html>

Here is the output:

Happy New Year!

Open the log file.
Write the log message.
Close the log file.

Display the view button.

The library is open from 9:00am to 9:00pm

The output matches my expectation perfectly!

Table of Contents

 About This Book

 Introduction of VBScript - Visual Basic Scripting Edition

 Variant Data Type, Subtypes, and Literals

 Arithmetic Operations

 Numeric Comparison Operations and Logical Operations

 String Operations - Concatenation and Comparison

 Variable Declaration and Assignment Statement

 Expression and Order of Operation Precedence

 Statement Syntax and Statement Types

 Array Data Type and Related Statements

 Array References and Array Assignment Statements

Conditional Statements - "If ... Then" and "Select Case"

 "If" Statements

"If" Statement Examples

 "Select Case" Statements

 "Select Case" Statement Examples

 Loop Statements - "For", "While", and "Do"

 "Function" and "Sub" Procedures

 Built-in Functions

 Inspecting Variables Received in Procedures

 Error Handling Flag and the "Err" Object

 Regular Expression Pattern Match and Replacement

 scrrun.dll - Scripting Runtime DLL Library

 Creating Your Own Classes

 IE Web Browser Supporting VBScript

 IIS ASP Server Supporting VBScript

 WSH (Windows Script Host)

 References

 Printable Copy - PDF Version

"If" Statement Examples - Updated in 2015, by Dr. Herong Yang