Vbscript Tutorial
Vbscript Tutorial
Vbscript Tutorial
Audience
This tutorial has been prepared for beginners to help them understand the basic-toadvanced functionality of VBScript. After completing this tutorial, you will find yourself at
a moderate level of expertise in using Microsoft VBScript from where you can take yourself
to the next levels.
Prerequisites
You need to have a good understanding of any computer programming language in order
to make the most of this tutorial. If you have done programming in any client-side
languages like Javascript, then it will be quite easy for you to learn the ropes of VBScript.
VBScript
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Overview .................................................................................................................................................. 2
Features of VBScript ........................................................................................................................................ 2
VBScript Version History and Uses ............................................................................................................... 2
Disadvantages.................................................................................................................................................. 2
Where VBScript is Today? ............................................................................................................................... 3
2.
Syntax ....................................................................................................................................................... 4
Your First VBScript ........................................................................................................................................... 4
Whitespace and Line Breaks ............................................................................................................................ 4
Formatting ....................................................................................................................................................... 4
Reserved Words .............................................................................................................................................. 5
Case Sensitivity ................................................................................................................................................ 6
Comments in VBScript ..................................................................................................................................... 7
3.
4.
Placements ............................................................................................................................................... 9
VBScript Placement in HTML File .................................................................................................................... 9
VBScript in <head>...</head> section ............................................................................................................. 9
VBScript in <body>...</body> section ........................................................................................................... 10
VBScript in <body> and <head> Sections ...................................................................................................... 10
VBScript in External File ................................................................................................................................. 11
VBScript Placement in QTP ............................................................................................................................ 12
5.
Variables ................................................................................................................................................. 13
VBScript Variables ......................................................................................................................................... 13
Declaring Variables ........................................................................................................................................ 13
Assigning Values to the Variables .................................................................................................................. 13
Scope of the Variables ................................................................................................................................... 14
6.
Constants ................................................................................................................................................ 18
Declaring Constants ....................................................................................................................................... 18
7.
Operators................................................................................................................................................ 20
What is an Operator? .................................................................................................................................... 20
The Arithmetic Operators .............................................................................................................................. 20
The Comparison Operators ........................................................................................................................... 22
The Logical Operators .................................................................................................................................... 25
The Concatenation Operators ....................................................................................................................... 27
8.
VBScript
Loops ...................................................................................................................................................... 39
For Loops ....................................................................................................................................................... 40
For...Each Loops............................................................................................................................................. 42
While...Wend Loop ........................................................................................................................................ 44
Do..While statement ..................................................................................................................................... 45
Do..Until Loops .............................................................................................................................................. 49
Loop Control Statements ............................................................................................................................... 53
Exit For statement ......................................................................................................................................... 53
Exit Do statement .......................................................................................................................................... 55
VBScript
VBScript
VBScript
vi
VBScript
1. OVERVIEW
VBScript
VBScript stands for Visual Basic Scripting that forms a subset of Visual Basic for
Applications (VBA). VBA is a product of Microsoft which is included NOT only in other
Microsoft products such as MS Project and MS Office but also in Third Party tools such as
AUTO CAD.
Features of VBScript
VBScript, for the most part, is case insensitive. It has a very simple syntax, easy
to learn and to implement.
It uses Component Object Model (COM) in order to access the elements of the
environment in which it is executing.
Active Server Pages (ASP), a server side scripting environment for creating
dynamic webpages which uses VBScript or Java Script.
Microsoft Outlook Forms usually runs on VBScript; however, the application level
programming relies on VBA (Outlook 2000 onwards).
Disadvantages
VBScript
2. SYNTAX
VBScript
Formatting
VBScript is based on Microsoft's Visual Basic. Unlike JavaScript, no statement terminators
such as semicolon is used to terminate a particular statement.
VBScript
Reserved Words
The following list shows the reserved words in VBScript. These reserved words SHOULD
NOT be used as a constant or variable or any other identifier names.
Loop
LSet
Me
Mod
New
Next
Not
Nothing
Null
On
Option
Optional
Or
ParamArray
Preserve
Private
Public
RaiseEvent
ReDim
Rem
Resume
RSet
Select
Set
Shared
Single
Static
Stop
Sub
Then
To
True
Type
VBScript
And
As
Boolean
ByRef
Byte
ByVal
Call
Case
Class
Const
Currency
Debug
Dim
Do
Double
Each
Else
ElseIf
Empty
End
EndIf
Enum
Eqv
Event
Exit
False
For
Function
Get
GoTo
If
Imp
Implements
In
Integer
Is
Let
Like
Long
TypeOf
Until
Variant
Wend
While
With
Xor
Eval
Execute
Msgbox
Erase
ExecuteGlobal
Option Explicit
Randomize
SendKeys
Case Sensitivity
VBScript is a case-insensitive language. This means that language keywords, variables,
function names and any other identifiers need NOT be typed with a consistent
6
VBScript
capitalization of letters. So identifiers int_counter, INT_Counter and INT_COUNTER have
the same meaning within VBScript.
Comments in VBScript
Comments are used to document the program logic and the user information with which
other programmers can seamlessly work on the same code in future. It can include
information such as developed by, modified by and it can also include incorporated logic.
Comments are ignored by the interpreter while execution. Comments in VBScript are
denoted by two methods.
Any statement that starts with a Single Quote () is treated as comment. Following is the
example:
<script language="vbscript" type="text/vbscript">
<!
' This Script is invoked after successful login
' Written by : TutorialsPoint
' Return Value : True / False
//- >
</script>
Any statement that starts with the keyword REM. Following is the example:
<script language="vbscript" type="text/vbscript">
<!
REM This Script is written to Validate the Entered Input
REM Modified by
: Tutorials point/user2
//- >
</script>
VBScript
Not all the modern browsers support VBScript. VBScript is supported just by Microsoft's
Internet Explorer while other browsers (Firefox and Chrome) support just JavaScript.
Hence, developers normally prefer JavaScript over VBScript.
Though Internet Explorer (IE) supports VBScript, you may need to enable or disable this
feature manually. This tutorial will make you aware of the procedure of enabling and
disabling VBScript support in Internet Explorer.
To disable VBScript support in your Internet Explorer, you need to select Disable radio
button under Active scripting.
4. PLACEMENTS
VBScript
In the following section, we will see how we can put VBScript in different ways:
VBScript
VBScript
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
It will produce the following result: Hello World message with a 'Say Hello' button. Upon
Clicking on the button a message box with a message "Hello World" is displayed to the
user.
11
VBScript
12
5. VARIABLES
VBScript
VBScript Variables
A variable is a named memory location used to hold a value that can be changed during
the script execution. VBScript has only ONE fundamental data type, Variant.
Declaring Variables
Variables are declared using dim keyword. Since there is only ONE fundamental data
type, all the declared variables are variant by default. Hence, a user NEED NOT mention
the type of data during declaration.
Example 1: In this Example, IntValue can be used as a String, Integer or even arrays.
Dim Var
Example 2: Two or more declarations are separated by comma(,)
Dim Variable1,Variable2
Rules
13
VBScript
Examples
' Below Example, The value 25 is assigned to the variable.
Value1 = 25
Dim
Public
Private
Dim
Variables declared using Dim keyword at a Procedure level are available only within the
same procedure. Variables declared using Dim Keyword at script level are available to
all the procedures within the same script.
Example: In the below example, the value of Var1 and Var2 are declared at script level
while Var3 is declared at procedure level.
Note: The scope of this chapter is to understand Variables. Functions would be dealt in
detail in the upcoming chapters.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim Var1
Dim Var2
14
VBScript
Call add()
Function add()
Var1 = 10
Var2 = 15
Dim Var3
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1
Msgbox Var2
Msgbox Var3
</script>
</body>
</html>
Public
Variables declared using "Public" Keyword are available to all the procedures across all the
associated scripts. When declaring a variable of type "public", Dim keyword is replaced by
"Public".
Example: In the following example, Var1 and Var2 are available at script level while Var3
is available across the associated scripts and procedures as it is declared as Public.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim Var1
Dim Var2
Public Var3
Call add()
Function add()
Var1 = 10
15
VBScript
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays 25, the sum of two values.
End Function
Msgbox Var1
Msgbox Var2
Msgbox Var3
</script>
</body>
</html>
Private
Variables that are declared as "Private" have scope only within that script in which they
are declared. When declaring a variable of type "Private", Dim keyword is replaced by
"Private".
Example: In the following example, Var1 and Var2 are available at Script Level. Var3 is
declared as Private and it is available only for this particular script. Use of "Private"
Variables is more pronounced within the Class.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim Var1
Dim Var2
Private Var3
Call add()
Function add()
Var1 = 10
Var2 = 15
Var3 = Var1+Var2
Msgbox Var3 'Displays the sum of two values.
End Function
Msgbox Var1
VBScript
Msgbox Var2
Msgbox Var3
</script>
</body>
</html>
17
6. CONSTANTS
VBScript
Constant is a named memory location used to hold a value that CANNOT be changed
during the script execution. If a user tries to change a Constant Value, the Script execution
ends up with an error. Constants are declared the same way the variables are declared.
Declaring Constants
Syntax
[Public | Private] Const Constant_Name = Value
The Constant can be of type Public or Private. The Use of Public or Private is Optional. The
Public constants are available for all the scripts and procedures while the Private Constants
are available within the procedure or Class. One can assign any value such as number,
String or Date to the declared Constant.
Example 1
In this example, the value of pi is 3.4 and it displays the area of the circle in a message
box.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim intRadius
intRadius = 20
const pi=3.14
Area = pi*intRadius*intRadius
Msgbox Area
</script>
</body>
</html>
18
VBScript
Example 2
The following example illustrates how to assign a String and Date Value to a Constant.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Example 3
In the following example, the user tries to change the Constant Value; hence, it will end
up with an Execution Error.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim intRadius
intRadius = 20
const pi=3.14
pi = pi*pi
Area = pi*intRadius*intRadius
Msgbox Area
</script>
</body>
</html>
19
7. OPERATORS
VBScript
What is an Operator?
Lets take an expression 4 + 5 is equal to 9. Here, 4 and 5 are called operands and + is
called the operator. VBScript language supports following types of operators:
Arithmetic Operators
Comparison Operators
Concatenation Operators
Description
Example
A + B will give 15
A - B will give -5
A * B will give 50
B / A will give 2
Exponentiation Operator
B ^ A
100000
will
give
20
VBScript
Example
Try the following example to understand all the arithmetic operators available in VBScript:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 5
Dim b : b = 10
Dim c
c = a+b
Document.write ("Addition Result is " &c)
Document.write ("<br></br>")
c = a-b
Document.write ("Subtraction Result is " &c)
Document.write ("<br></br>")
c = a*b
Document.write ("Multiplication Result is " &c)
Document.write ("<br></br>")
c = b/a
Document.write ("Division Result is " &c)
Document.write ("<br></br>")
c = b MOD a
Document.write ("Modulus Result is " &c)
Document.write ("<br></br>")
c = b^a
Document.write ("Exponentiation Result is " &c)
Document.write ("<br></br>")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Addition Result is 15
Subtraction Result is -5
21
VBScript
Multiplication Result is 50
Division Result is 2
Modulus Result is 0
Exponentiation Result is 100000
Description
Example
==
(A == B) is
False.
<>
(A <> B) is
True.
>
(A > B) is
False.
<
(A < B) is
True.
>=
(A >= B) is
False.
<=
(A <= B) is
True.
Example
Try the following example to understand all the Comparison operators available in
VBScript:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 10
22
VBScript
Dim b : b = 20
Dim c
If a=b Then
Document.write ("Operator Line 1 : True")
Document.write ("<br></br>")
Else
Document.write ("Operator Line 1 : False")
Document.write ("<br></br>")
End If
If a<>b Then
Document.write ("Operator Line 2 : True")
Document.write ("<br></br>")
Else
Document.write ("Operator Line 2 : False")
Document.write ("<br></br>")
End If
If a>b Then
Document.write ("Operator Line 3 : True")
Document.write ("<br></br>")
Else
Document.write ("Operator Line 3 : False")
Document.write ("<br></br>")
End If
If a<b Then
Document.write ("Operator Line 4 : True")
Document.write ("<br></br>")
Else
Document.write ("Operator Line 4 : False")
Document.write ("<br></br>")
End If
If a>=b Then
23
VBScript
If a<=b Then
Document.write ("Operator Line 6 : True")
Document.write ("<br></br>")
Else
Document.write ("Operator Line 6 : False")
Document.write ("<br></br>")
End If
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Operator Line 1 : False
24
VBScript
Description
Example
AND
OR
a<>0 OR b<>0
is true.
NOT
NOT(a<>0
OR
b<>0) is false.
XOR
(a<>0
XOR
b<>0) is false.
Example
Try the following example to understand all the Logical operators available in VBScript:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 10
Dim b : b = 0
Dim c
Else
Document.write ("AND Operator Result is : False")
Document.write ("<br></br>")
End If
25
VBScript
26
VBScript
Description
Example
A + B will give 15
&
Example
Try the following example to understand the Concatenation operator available in VBScript:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 5
Dim b : b = 10
Dim c
c=a+b
Document.write ("Concatenated value:1 is " &c) 'Numeric addition
Document.write ("<br></br>")
c=a&b
Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers
Document.write ("<br></br>")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Concatenated value:1 is 15
Concatenated value:2 is 510
27
VBScript
Concatenation can also be used for concatenating two strings. Assume variable
A="Microsoft" and variable B="VBScript" then:
Operator
Description
Example
&
Example
Try the following example to understand the Concatenation operator available in VBScript:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = "Microsoft"
Dim b : b = "VBScript"
Dim c
c=a+b
Document.write ("Concatenated value:1 is " &c) 'Numeric addition
Document.write ("<br></br>")
c=a&b
Document.write ("Concatenated value:2 is " &c) 'Concatenate two numbers
Document.write ("<br></br>")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Concatenated value:1 is MicrosoftVBScript
Concatenated value:2 is MicrosoftVBScript
28
8. DECISION MAKING
VBScript
Decision making allows programmers to control the execution flow of a script or one of its
sections. The execution is governed by one or more conditional statements.
Following is the general form of a typical decision making structure found in most of the
programming languages:
if statement
if..else statement
if...elseif..else statement
Description
An if statement consists of a Boolean expression followed by
one or more statements.
29
VBScript
nested if statements
switch statement
If Statements
An If statement consists of a Boolean expression followed by one or more statements. If
the condition is said to be True, the statements under If condition(s) are Executed. If the
Condition is said to be False, the statements after the If loop are executed.
Syntax
The syntax of an If statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
End If
Flow Diagram
30
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 20
Dim b : b = 10
If a > b Then
Document.write "a is Greater than b"
End If
</script>
</body>
</html>
When the above code is executed, it produces the following result:
a is Greater than b
IfElse Statements
An If statement consists of a Boolean expression followed by one or more statements. If
the condition is said to be True, the statements under If condition(s) are Executed. If the
Condition is said to be False, the statements under Else Part would be executed.
Syntax
The syntax of an ifelse statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
Else
Statement 1
.....
....
Statement n
31
VBScript
End If
Flow Diagram
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a = 5
Dim b : b = 25
If a > b Then
Document.write "a is Greater"
Else
Document.write "b is Greater"
End If
</script>
</body>
</html>
32
VBScript
When the above code is executed, it produces the following result:
b is Greater
If..ElseIf..Else Statements
An If statement followed by one or more ElseIf Statements that consists of boolean
expressions and then followed by a default else statement, which executes when all the
condition becomes false.
Syntax
The syntax of an If-ElseIf-Else statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
Else
Statement 1
.....
....
Statement n
End If
33
VBScript
Flow Diagram
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a
a = -5
If a > 0 Then
Document.write "a is a POSITIVE Number"
ElseIf a < 0 Then
Document.write "a is a NEGATIVE Number"
Else
Document.write "a is EQUAL than ZERO"
End If
</script>
</body>
34
VBScript
</html>
When the above code is executed, it produces the following result:
a is a NEGATIVE Number
Nested If Statement
An If or ElseIf statement inside another If or ElseIf statement(s). The Inner If
statements are executed based on the Outermost If statements. This enables VBScript to
handle complex conditions with ease.
Syntax
The syntax of a Nested if statement in VBScript is:
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
Else
Statement 1
.....
....
Statement n
End If
Else
Statement 1
.....
....
35
VBScript
Statement n
End If
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a
a = 23
If a > 0 Then
Document.write "The Number is a POSITIVE Number"
If a = 1 Then
Document.write "The Number is Neither Prime NOR Composite"
Elseif a = 2 Then
Document.write "The Number is the Only Even Prime Number"
Elseif a = 3 Then
Document.write "The Number is the Least Odd Prime Number"
Else
Document.write "The Number is NOT 0,1,2 or 3"
End If
ElseIf
a < 0 Then
36
VBScript
Switch Statements
When a user wants to execute a group of statements depending upon a value of an
expression, then he can use Switch Case statements. Each value is called a Case, and the
variable being switched ON based on each case. Case Else statement is executed if test
expression doesn't match any of the Case specified by the user.
Case Else is an optional statement within Select Case, however, it is a good programming
practice to always have a Case Else statement.
Syntax
The syntax of a Switch Statement in VBScript is:
Select Case expression
Case expressionlist1
statement1
statement2
....
....
statement1n
Case expressionlist2
statement1
statement2
....
....
Case expressionlistn
statement1
statement2
....
....
Case Else
elsestatement1
elsestatement2
....
....
End Select
Example
<!DOCTYPE html>
<html>
37
VBScript
<body>
<script language="vbscript" type="text/vbscript">
Dim MyVar
MyVar = 1
38
9. LOOPS
VBScript
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow more complicated
execution paths. A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in VBScript.
VBScript provides the following types of loops to handle looping requirements. Click the
following links to check their detail.
Loop Type
Description
for loop
while..wend loop
39
VBScript
do..while loops
do..until loops
For Loops
A for loop is a repetition control structure that allows a developer to efficiently write a loop
that needs to execute a specific number of times.
Syntax
The syntax of a for loop in VBScript is:
For counter = start To end [Step stepcount]
[statement 1]
[statement 2]
....
[statement n]
[Exit For]
[statement 11]
[statement 22]
....
[statement n]
Next
40
VBScript
Flow Diagram
The For step is executed first. This step allows you to initialize any loop control
variables and increment the step counter variable.
Secondly, the condition is evaluated. If it is true, the body of the loop is executed.
If it is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the For Loop.
After the body of the for loop executes, the flow of control jumps to the Next
statement. This statement allows you to update any loop control variables. It is
updated based on the step counter value.
The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After
the condition becomes false, the For Loop terminates.
41
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a=10
For i=0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
Next
</script>
</body>
</html>
When the above code is compiled and executed, it produces the following result:
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 6
The value is i is : 8
The value is i is : 10
For...Each Loops
A For Each loop is used when we want to execute a statement or a group of statements
for each element in an array or collection.
A For Each loop is similar to For Loop; however, the loop is executed for each element in
an array or group. Hence, the step counter won't exist in this type of loop and it is mostly
used with arrays or used in context of File system objects in order to operate recursively.
Syntax
42
VBScript
The syntax of a For Each loop in VBScript is:
For Each element In Group
[statement 1]
[statement 2]
....
[statement n]
[Exit For]
[statement 11]
[statement 22]
Next
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
'fruits is an array
fruits=Array("apple","orange","cherries")
Dim fruitnames
msgbox fruitnames
</script>
</body>
</html>
When the above code is executed, it prints all the fruitnames with one item in each line.
apple
43
VBScript
orange
cherries
While...Wend Loop
In a While..Wend loop, if the condition is True, all statements are executed untilWend
keyword is encountered.
If the condition is false, the loop is exited and the control jumps to very next statement
after Wend keyword.
Syntax
The syntax of a While..Wend loop in VBScript is:
While condition(s)
[statements 1]
[statements 2]
...
[statements n]
Wend
Flow Diagram
Example
44
VBScript
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim Counter :
Counter = 10
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The Current Value of the Counter is : 11
Do..While statement
A Do..While loop is used when we want to repeat a set of statements as long as the
condition is true. The Condition may be checked at the beginning of the loop or at the end
of the loop.
Syntax
The syntax of a Do..While loop in VBScript is:
Do While condition
[statement 1]
[statement 2]
45
VBScript
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop
Flow Diagram
Example
The below example uses Do..while loop to check the condition at the beginning of the
loop. The statements inside the loop are executed only if the condition becomes True.
<!DOCTYPE html>
<html>
<body>
46
VBScript
Do While i < 5
i = i + 1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 1
The value of i is : 2
The value of i is : 3
The value of i is : 4
The value of i is : 5
Alternate Syntax
There is an alternate Syntax for Do..while loop which checks the condition at the end of
the loop. The Major difference between these two syntax is explained below with an
example.
Do
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
47
VBScript
Flow Diagram
Example
The below example uses Do..while loop to check the condition at the end of the loop. The
Statements inside the loop are executed at least once even if the condition is False.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
i=10
Do
i = i + 1
Document.write("The value of i is : " & i)
48
VBScript
Document.write("<br></br>")
Loop While i<3 'Condition is false.Hence loop is executed once.
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 11
Do..Until Loops
A Do..Until loop is used when we want to repeat a set of statements as long as the
condition is false. The Condition may be checked at the beginning of the loop or at the end
of loop.
Syntax
The syntax of a Do..Until loop in VBScript is:
Do Until condition
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop
Flow Diagram
49
VBScript
Example
The following example uses Do..Until loop to check the condition at the beginning of the
loop. The Statements inside the loop are executed only if the condition is false. It exits out
of the loop when the condition becomes true.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
i=10
Do Until i>15
i = i + 1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop
</script>
50
VBScript
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value of i is : 11
The value of i is : 12
The value of i is : 13
The value of i is : 14
The value of i is : 15
The value of i is : 16
Alternate Syntax
There is an alternate Syntax for Do..Until loop which checks the condition at the end of
the loop. The Major difference between these two syntax is explained below with an
example.
Do
[statement 1]
[statement 2]
...
[statement n]
[Exit Do]
[statement 1]
[statement 2]
...
[statement n]
Loop Until condition
Flow Diagram
51
VBScript
Example
The below example uses Do..Until loop to check the condition at the end of the loop. The
Statements inside the loop are executed at least once even if the condition is True.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
i=10
Do
i = i + 1
Document.write("The value of i is : " & i)
Document.write("<br></br>")
Loop Until i<15 'Condition is True.Hence loop is executed once.
</script>
</body>
52
VBScript
</html>
When the above code is executed, it prints the following output in the console.
The value of i is : 11
Description
Exit Do statement
Syntax
The syntax for Exit For Statement in VBScript is:
Exit For
Flow Diagram
53
VBScript
Example
The following example uses Exit For. If the value of the Counter reaches 4, the For Loop
is Exited and control jumps to the next statement immediately after the For Loop.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a : a=10
For i=0 to a Step 2 'i is the counter variable and it is incremented by 2
document.write("The value is i is : " & i)
document.write("<br></br>")
If i=4 Then
i=i*10
VBScript
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40
Exit Do statement
An Exit Do Statement is used when we want to Exit the Do Loops based on certain criteria.
It can be used within both Do..While and Do..Until Loops.
When Exit Do is executed, the control jumps to next statement immediately after the Do
Loop.
Syntax
The syntax for Exit Do Statement in VBScript is:
Exit Do
Flow Diagram
55
VBScript
Example
The following example uses Exit Do. If the value of the Counter reaches 10, the Do Loop
is Exited and control jumps to the next statement immediately after the For Loop.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
i = 0
Do While i <= 100
If i > 10 Then
Exit Do
End If
document.write("The Value of i is : " &i)
document.write("<br></br>")
i = i + 2
Loop
</script>
</body>
</html>
When the above code is executed, it prints the following output on the console.
The Value of i is : 0
The Value of i is : 2
The Value of i is : 4
The Value of i is : 6
The Value of i is : 8
The Value of i is : 10
56
10. EVENTS
VBScript
What is an Event ?
VBScript's interaction with HTML is handled through events that occur when the user or
browser manipulates a page. When the page loads, that is an event. When the user clicks
a button, that click too is an event. Other examples of events include pressing any key,
closing window, resizing window, etc. Developers can use these events to execute VBScript
coded responses, which cause buttons to close windows, messages to be displayed to
users, data to be validated, and virtually any other type of response imaginable to occur.
Events are a part of the Document Object Model (DOM) and every HTML element has a
certain set of events, which can trigger VBScript Code. Please go through this small tutorial
for a better understanding HTML Event Reference. Here, we will see few examples to
understand a relation between Event and VBScript.
Example
<html>
<head>
<script language="vbscript" type="text/vbscript">
Function sayHello()
msgbox "Hello World"
End Function
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello"/>
</body>
</html>
It will produce the following result, and when you click the Hello button, the onclick event
will occur which will trigger sayHello() function.
57
VBScript
Example
<html>
<head>
</head>
<body>
<script language="VBScript">
Function fnSubmit()
Msgbox("Hello Tutorialspoint.Com")
End Function
</script>
<form action="/cgi-bin/test.cgi" method="post" name="form1"
onSubmit="fnSubmit()">
<input name="txt1" type="text"><br>
<input name="btnButton1" type="submit" value="Submit">
</form>
</script>
</body>
</html>
Example
<html>
<head>
</head>
58
VBScript
<body>
<script language="VBScript">
Function AlertMsg
Msgbox("ALERT !")
End Function
Function onmourse_over()
Msgbox("Onmouse Over")
End Function
Sub txt2_OnMouseOut()
Msgbox("Onmouse Out !!!")
End Sub
Sub btnButton_OnMouseOut()
Msgbox("onmouse out on Button !")
End Sub
</script>
<form action="page.cgi" method="post" name="form1">
<input name="txt1" type="text" OnMouseOut="AlertMsg()"><br>
<input name="txt2" type="text" OnMouseOver="onmourse_over()">
<br><input name="btnButton" type="button" value="Submit">
</form>
</body>
</html>
It will produce a result when you hover the mouse over the text box and also when you
move the focus away from the text box and the button.
59
VBScript
Event
Value
Description
Onchange
script
Onsubmit
script
Onreset
script
Onblur
script
Onfocus
script
onkeydown
script
onkeypress
script
Onkeyup
script
Onclick
script
Ondblclick
script
onmousedown
script
onmousemove
script
onmouseout
script
onmouseover
script
onmouseup
script
60
VBScript
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on your site, the browser sends the
same cookie to the server for retrieval. Once retrieved, your server knows/remembers
what was stored earlier. Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.
Path: The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key and value pairs.
Cookies were originally designed for CGI programming and cookies' data is automatically
transmitted between the web browser and web server, so CGI scripts on the server can
read and write cookie values that are stored on the client.
VBScript can also manipulate cookies using the cookie property of the Document object.
VBScript can read, create, modify and delete the cookie or cookies that apply to the current
web page.
Storing Cookies
The simplest way to create a cookie is
document.cookieobject, which looks like this:
to
assign
string
value
to
the
61
VBScript
Syntax
document.cookie = "key1=value1;key2=value2;expires=date"
Here expires attribute is optional. If you provide this attribute with a valid date or time,
then cookie will expire at the given date or time and after that cookies' value will not be
accessible.
Example
Following is the example to set a customer name in input cookie.
<html>
<head>
<script type="text/vbscript">
Function WriteCookie
If document.myform.customer.value="" Then
msgbox "Enter some value!"
Else
cookievalue=(document.myform.customer.value)
document.cookie="name=" + cookievalue
msgbox "Setting Cookies : " & "name=" & cookievalue
End If
End Function
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
It will produce the following result. Now enter something in the textbox and press the
button "Set Cookie" to set the cookies.
62
VBScript
Now, your system has a cookie called name. You can set multiple cookies using multiple
key=value pairs separated by comma. You will learn how to read this cookie in next
section.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So, you can use this string whenever you want to
access the cookie. The document.cookie string will keep a list of name=value pairs
separated by semicolons where name is the name of a cookie and value is its string value.
You can use strings' split() function to break the string into key and values as follows:
Example
Following is the example to get the cookies set in the previous section:
<html>
<head>
<script type="text/vbscript">
Function ReadCookie
allcookies = document.cookie
msgbox "All Cookies : " + allcookies
cookiearray
= split(allcookies,";")
= Split(cookiearray(i),"=")
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
63
VBScript
</body>
</html>
Note : Here, UBound is a method of Array class, which returns the length of an array. We
will discuss Arrays in a separate chapter; until that time, please try to digest it.
It will produce the following result. Now, press the button "Get Cookie" to see the cookies,
which you have set in previous section.
Note: There may be some other cookies already set on your system. So, tnhe above code
will show you all the cookies set on your system.
Example
The following example illustrates how to set cookie expiration date after 1 Month:
<html>
<head>
<script type="text/vbscript">
Function WriteCookie()
x = now()
y = dateadd("m",1,now())
cookievalue = document.myform.customer.value
document.cookie = "name = "
& cookievalue
VBScript
</form>
</body>
</html>
Deleting a Cookie
Sometimes, you will want to delete a cookie so that subsequent attempts to read the
cookie return nothing. To do this, you just need to set the expiration date to a time in the
past.
Example
The following example illustrates how to delete a cookie by setting its expiration date 1
Month in the past:
<html>
<head>
<script type="text/vbscript">
Function WriteCookie()
x = now()
x = now()
a = Month(x)-1
b = day(x)
c = year(x)
d = DateSerial(c,a,b)
e = hour(x)
msgbox e
f = minute(x)
msgbox f
d = cdate(d & " " & e & ":" & f)
msgbox d
cookievalue = document.myform.customer.value
document.cookie = "name = "
& cookievalue
VBScript
66
VBScript
Number functions help the developers to handle numbers in an efficient way and also helps
them to convert their subtypes. It also helps them to make use of the inbuilt mathematical
functions associated with VBScript.
Description
CDbl
CInt
CLng
CSng
Hex
Example
Try the following example to understand all the Number Conversion Functions available in
VBScript.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
67
VBScript
x = 123
y = 123.882
document.write("x value after converting to double - " & CDbl(x) & "<br />")
document.write("y value after converting to double - " & CDbl(y) & "<br />")
document.write("x value after converting to Int -" & CInt(x) & "<br />")
document.write("y value after converting to Int -" & CInt(y) & "<br />")
document.write("x value after converting to Long -" & CLng(x) & "<br />")
document.write("y value after converting to Long -" & CLng(y) & "<br />")
document.write("x value after converting to Single -" & CSng(x) & "<br />")
document.write("y value after converting to Single -" & CSng(y) & "<br />")
document.write("x value after converting to Hex -" & Hex(x) & "<br />")
document.write("y value after converting to Hex -" & Hex(y) & "<br />")
</script>
</body>
</html>
When executed, the above script will produce the following output:
x value after converting to double - 123
y value after converting to double - 123.882
x value after converting to Int -123
y value after converting to Int -124
x value after converting to Long -123
y value after converting to Long -124
x value after converting to Single -123
y value after converting to Single -123.882
x value after converting to Hex -7B
y value after converting to Hex -7C
Function
Description
68
VBScript
FormatNumber
FormatPercent
Description
Settings
The above parameters LeadingDig, UseParForNegNum and GroupDigits arguments can
have any of the following settings:
-1 = vbTrue - True
0 = vbFalse - False
Example
Try the following example to understand all the Number Formatting Functions available in
VBScript.
69
VBScript
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When executed, the above script will produce the following output:
Line 1 : -645.999
Line 2 : (645.999)
Line 3 : -645.999
Line 4 : -64,599.865%
Line 5 : (64,599.865%)
Line 6 : -64599.865%
70
VBScript
Mathematical Functions
Mathematical Functions help us to evaluate the mathematical and trigonometrical
functions of a given input number.
Function
Description
Int
Fix
Log
Oct
Hex
Rnd
Sgn
Sqr
A Function, which returns the square root of the given number. Negative
numbers disallowed
Abs
Exp
Sin
Cos
Tan
VBScript
Example
Try the following example to understand all the inbuilt Mathematical Functions available
in VBScript.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
72
VBScript
VBScript
74
13. STRINGS
VBScript
Strings are a sequence of characters, which can consist of alphabets or numbers or special
characters or all of them. A variable is said to be a string if it is enclosed within double
quotes " ".
Syntax
variablename = "string"
Examples
str1 = "string"
str2 = "132.45"
str3 = "!@#$;*"
Str4 = "Asc23@#"
String Functions
There are predefined VBScript String functions, which help the developers to work with
the strings very effectively. Below are String methods that are supported in VBScript.
Please click on each one of the methods to know in detail.
Function
Name
Description
InStr
InstrRev
Lcase
Ucase
Left
Returns a specific number of characters from the left side of the string.
Right
75
VBScript
Mid
Ltrim
Returns a string after removing the spaces on the left side of the
specified string.
Rtrim
Returns a string after removing the spaces on the right side of the
specified string.
Trim
Returns a string value after removing both leading and trailing blank
spaces.
Len
Replace
Space
StrComp
String
StrReverse
InStr Function
The InStr Function returns the first occurrence of one string within another string. The
search happens from left to right.
Syntax
InStr([start,]string1,string2[,compare])
Description
Start, an Optional Parameter. Specifies the starting position for the search. The
search begins at the first position from left to right.
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & InStr(1,var,"s") & "<br />")
document.write("Line 2 : " & InStr(7,var,"s") & "<br />")
document.write("Line 3 : " & InStr(1,var,"f",1) & "<br />")
document.write("Line 4 : " & InStr(1,var,"t",0) & "<br />")
document.write("Line 5 : " & InStr(1,var,"i") & "<br />")
document.write("Line 6 : " & InStr(7,var,"i") & "<br />")
document.write("Line 7 : " & InStr(var,"VB"))
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : 6
Line 2 : 0
Line 3 : 8
Line 4 : 9
Line 5 : 2
Line 6 : 16
Line 7 : 11
InStrRev Function
The InStrRev Function returns the first occurrence of one string within another string. The
Search happens from right to Left.
77
VBScript
Syntax
InStrRev(string1,string2[,start,[compare]])
Description
Start, an Optional Parameter. Specifies the Starting position for the search. The
Search begins at the first position from right to left.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & InStrRev(var,"s",10) & "<br />")
document.write("Line 2 : " & InStrRev(var,"s",7) & "<br />")
document.write("Line 3 : " & InStrRev(var,"f",-1,1) & "<br />")
document.write("Line 4 : " & InStrRev(var,"t",5) & "<br />")
document.write("Line 5 : " & InStrRev(var,"i",7) & "<br />")
document.write("Line 6 : " & InStrRev(var,"i",7) & "<br />")
document.write("Line 7 : " & InStrRev(var,"VB",1))
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : 6
Line 2 : 6
Line 3 : 8
78
VBScript
Line 4 : 0
Line 5 : 2
Line 6 : 2
Line 7 : 0
LCase Function
The LCase Function returns the string after converting the entered string into lower case
letters.
Syntax
Lcase(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & LCase(var) & "<br />")
var="MS VBSCRIPT"
document.write("Line 2 : " & LCase(var) & "<br />")
var="microsoft"
document.write("Line 3 : " & LCase(var) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : microsoft vbscript
Line 2 : ms vbscript
Line 3 : microsoft
79
VBScript
UCase Function
The UCase Function returns the string after converting the entered string into UPPER case
letters.
Syntax
UCase(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & UCase(var) & "<br />")
var="MS VBSCRIPT"
document.write("Line 2 : " & UCase(var) & "<br />")
var="microsoft"
document.write("Line 3 : " & UCase(var) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : MICROSOFT VBSCRIPT
Line 2 : MS VBSCRIPT
Line 3 : MICROSOFT
Left Function
The Left Function returns a specified number of characters from the left side of the given
input string.
Syntax
Left(String, Length)
80
VBScript
String, a Required Parameter. Input String from which the specified number of
characters to be returned from left side.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & Left(var,2) & "<br />")
var="MS VBSCRIPT"
document.write("Line 2 : " & Left(var,5) & "<br />")
var="microsoft"
document.write("Line 3 : " & Left(var,9) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : Mi
Line 2 : MS VB
Line 3 : microsoft
Right Function
The Right Function returns a specified number of characters from the right side of the
given input string.
Syntax
Right(String, Length)
String, a Required Parameter. Input String from which the specified number of
characters to be returned from Right side.
81
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & Right(var,2) & "<br />")
var="MS VBSCRIPT"
document.write("Line 2 : " & Right(var,5) & "<br />")
var="microsoft"
document.write("Line 3 : " & Right(var,9) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : pt
Line 2 : CRIPT
Line 3 : microsoft
Mid Function
The Mid Function returns a specified number of characters from a given input string.
Syntax
Mid(String,start[,Length])
String, a Required Parameter. Input String from which the specified number of
characters to be returned.
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var="Microsoft VBScript"
document.write("Line 1 : " & Mid(var,2) & "<br />")
document.write("Line 2 : " & Mid(var,2,5) & "<br />")
document.write("Line 3 : " & Mid(var,5,7) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : icrosoft VBScript
Line 2 : icros
Line 3 : osoft V
LTrim Function
The Ltrim Function removes the blank spaces that are there on the left side of the string.
Syntax
LTrim(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var =
"
Microsoft VBScript"
83
VBScript
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
After Ltrim : Microsoft VBScript
RTrim Function
The Rtrim Function removes the blank spaces that are there on the Right side of the string.
Syntax
RTrim(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var =
"Microsoft VBScript
"
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
After Rtrim : Microsoft VBScript
Trim Function
The Trim Function removes both the Leading and Trailing blank spaces of the given input
string.
84
VBScript
Syntax
Trim(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var =
"
Microsoft VBScript
"
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
After trim : Microsoft VBScript
Len Function
The Len Function returns the length of the given input string including the blank spaces.
Syntax
Len(String)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var1 =
"Microsoft VBScript"
var2 =
"
Microsoft VBScript
"
85
VBScript
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Length of var1 is : 18
Length of var2 is : 36
Replace Function
The Replace Function replaces a specified part of a string with a specific string a specified
number of times.
Syntax
Replace(string,find,replacewith[,start[,count[,compare]]])
string, a Required Parameter. The Input String from to be searched for replacing.
find, a Required Parameter. The Part of the String that will be be replaced.
replace with, a Required Parameter. The replacement string, which would be replaced
against the find parameter.
start, an Optional Parameter. Specifies the start position from where the string has
to be searched and replaced. Default value is 1.
count, an Optional Parameter. Specifies the number of times the replacement has to
be performed.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
86
VBScript
'VB to be replaced by vb
document.write("Line 2: " & Replace(var,"VB","vb") & "<br />")
''is' replaced by ##
document.write("Line 3: " & Replace(var,"is","##") & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming
87
VBScript
Space Function
The Space Function fills a string with a specific number of spaces.
Syntax
space(number)
number, a Required Parameter. The number of spaces that we want to add to the given
string.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var1="Microsoft"
var2="VBScript"
document.write(var1 & Space(2)& var2)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Microsoft VBScript
StrComp Function
The StrComp Function returns an integer value after comparing the two given strings. It
can return any of the three values -1, 0 or 1 based on the input strings to be compared.
Syntax
StrComp(string1,string2[,compare])
88
VBScript
Description
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 :0
Line 2 :1
Line 3 :1
Line 4 :0
Line 5 :1
89
VBScript
String Function
The String Function fills a string with the specified character the specified number of times.
Syntax
String(number,character)
Number, a Required Parameter. An integer value, which would be repeated for the
specified number of times against the character parameter.
Character, a Required Parameter. Character value, which has to be repeated for the
specified number of times.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 :$$$
Line 2 :****
Line 3 :ddddd
Line 4 :AAAAAA
90
VBScript
StrReverse Function
The StrReverse Function reverses the specified string.
Syntax
StrReverse(string)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : TPIRCSBV
Line 2 : tpircSBV tsriF yM
Line 3 : 54.321
91
14. ARRAYS
VBScript
What is an Array?
We know very well that a variable is a container to store a value. Sometimes, developers
are in a position to hold more than one value in a single variable at a time. When a series
of values is stored in a single variable, then it is known as an array variable.
Array Declaration
Arrays are declared the same way a variable has been declared except that the declaration
of an array variable uses parenthesis. In the following example, the size of the array is
mentioned in the brackets.
'Method 1 : Using Dim
Dim arr1() 'Without Size
Although, the Array size is indicated as 5, it can hold 6 values as array index starts
from ZERO.
VBScript Arrays can store any type of variable in an array. Hence, an array can store
an integer, string or characters in a single array variable.
Example
<!DOCTYPE html>
<html>
<body>
92
VBScript
Dim arr(5)
arr(0) = "1"
'Number as String
arr(1) = "VBScript"
'String
arr(2) = 100
'Number
arr(3) = 2.45
'Decimal Number
arr(4) = #10/07/2013#
'Date
'Time
document.write("Value stored in Array index 0 : " & arr(0) & "<br />")
document.write("Value stored in Array index 1 : " & arr(1) & "<br />")
document.write("Value stored in Array index 2 : " & arr(2) & "<br />")
document.write("Value stored in Array index 3 : " & arr(3) & "<br />")
document.write("Value stored in Array index 4 : " & arr(4) & "<br />")
document.write("Value stored in Array index 5 : " & arr(5) & "<br />")
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM
Multi-Dimension Arrays
Arrays are not just limited to single dimension and can have a maximum of 60 dimensions.
Two-dimension arrays are the most commonly used ones.
93
VBScript
Example
In the following example, a multi-dimension array is declared with 3 rows and 4 columns.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim arr(2,3)
arr(0,0) = "Apple"
arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(0,3) = "pineapple"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
arr(1,2) = "carrot"
arr(1,3) = "tomato"
arr(2,0) = "potato"
arr(2,1) = "sandwitch"
arr(2,2) = "coffee"
arr(2,3) = "nuts"
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
Value stored in Array index : 0 , 1 : Orange
Value stored in Array index : 2 , 2 : coffee
ReDim Statement
ReDim Statement is used to declare dynamic-array variables and allocate or reallocate
storage space.
94
VBScript
varname - A Required parameter, which denotes Name of the variable, which should
follow the standard variable naming conventions.
Example
In the below example, an array has been redefined and then preserved the values when
the existing size of the array is changed.
Note : Upon resizing an array smaller than it was originally, the data in the eliminated
elements will be lost.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim a()
i=0
redim a(5)
a(0)="XYZ"
a(1)=41.25
a(2)=22
VBScript
When we save the above script as HTML and execute it in Internet Explorer, it produces
the following result.
XYZ
41.25
22
3
4
5
6
7
Array Methods
There are various inbuilt functions within VBScript which help the developers to handle
arrays effectively. All the methods that are used in conjunction with arrays are listed
below. Please click on the method name to know in detail.
Function
Description
LBound
UBound
Split
Join
Filter
IsArray
Erase
A Function, which recovers the allocated memory for the array variables.
96
VBScript
LBound Function
The LBound Function returns the smallest subscript of the specified array. Hence, LBound
of an array is ZERO.
Syntax
LBound(ArrayName[,dimension])
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim arr(5)
arr(0) = "1"
'Number as String
arr(1) = "VBScript
'String
arr(2) = 100
'Number
arr(3) = 2.45
'Decimal Number
arr(4) = #10/07/2013#
'Date
'Time
</script>
97
VBScript
</body>
</html>
When the above code is saved as .html and executed in Internet Explorer, it produces the
following result:
The smallest Subscript value of the given array is : 0
The smallest Subscript of the first dimension of arr2 is : 0
The smallest Subscript of the Second dimension of arr2 is : 0
UBound Function
The UBound Function returns the Largest subscript of the specified array. Hence, this value
corresponds to the size of the array.
Syntax
UBound(ArrayName[,dimension])
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim arr(5)
arr(0) = "1"
'Number as String
arr(1) = "VBScript"
'String
arr(2) = 100
'Number
arr(3) = 2.45
'Decimal Number
arr(4) = #10/07/2013#
'Date
'Time
VBScript
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, then it
produces the following result:
The Largest Subscript value of the given array is : 5
The Largest Subscript of the first dimension of arr2 is : 3
The Largest Subscript of the Second dimension of arr2 is : 2
Split Function
A Split Function returns an array that contains a specific number of values split based on
a Delimiter.
Syntax
Split(expression[,delimiter[,count[,compare]]])
expression, a Required parameter. The String Expression that can contain strings
with delimiters.
Example
<!DOCTYPE html>
99
VBScript
<html>
<body>
<script language="vbscript" type="text/vbscript">
Next
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
The value of array in 0 is :Red
The value of array in 1 is : Blue
The value of array in 2 is : Yellow
Join Function
A Function, which returns a String that contains a specified number of substrings in an
array. This is an exact opposite function of Split Method.
Syntax
Join(List[,delimiter])
List, a Required parameter. An Array that contains the substrings that are to be
joined.
Example
<!DOCTYPE html>
<html>
100
VBScript
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When the above code is saved as .html and executed in Internet Explorer, it produces the
following result:
The value of b is :Red Blue Yellow
The Join result after using delimiter is : Red$Blue$Yellow
Filter Function
A Filter Function, which returns a zero-based array that contains a subset of a string array
based on a specific filter criteria.
Syntax
Filter(inputstrings,value[,include[,compare]])
what
string
101
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
a= array("Red","Blue","Yellow")
b = Filter(a,"B")
c = Filter(a,"e")
d = Filter(a,"Y")
For each x in b
Document.write("The Filter result 1: " & x & "<br />")
Next
For each y in c
Document.write("The Filter result 2: " & y & "<br />")
Next
For each z in d
Document.write("The Filter result 3: " & z & "<br />")
Next
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
The Filter result 1: Blue
The Filter result 2: Red
The Filter result 2: Blue
The Filter result 2: Yellow
The Filter result 3: Yellow
102
VBScript
IsArray Function
The IsArray Function returns a Boolean value that indicates whether or NOT the specified
input variable is an array variable.
Syntax
IsArray(variablename)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
a = array("Red","Blue","Yellow")
b = "12345"
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
The IsArray result 1 : True
The IsArray result 2 : False
Erase Function
The Erase Function is used to reset the values of fixed size arrays and free the memory of
the dynamic arrays. It behaves depending upon the type of the arrays.
Syntax
Erase ArrayName
103
VBScript
Fixed String array, each element in an array is reset to Zero length " ".
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim NumArray(3)
NumArray(0) = "VBScript"
NumArray(1) = 1.05
NumArray(2) = 25
NumArray(3) = #23/04/2013#
Dim DynamicArray()
ReDim DynamicArray(9)
Erase NumArray
Erase DynamicArray
</script>
</body>
</html>
When the above code is saved as .HTML and executed in Internet Explorer, it produces
the following result:
The value at Zero index of NumArray is
The value at First index of NumArray is
104
VBScript
105
VBScript
VBScript Date and Time Functions help the developers to convert date and time from one
format to another or to express the date or time value in the format that suits a specific
condition.
Date Functions
Function
Description
Date
CDate
DateAdd
DateDiff
DatePart
DateSerial
A Function, which returns a valid date for the given year, month,
and date
FormatDateTime
IsDate
Day
Month
Year
106
VBScript
MonthName
WeekDay
WeekDayName
A Function, which returns the weekday name for the specified day.
Date Function
The Function returns the current system Date.
Syntax
date()
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
a = date()
document.write("The Value of a : " & a)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
The Value of a : 19/07/2013
CDate Function
The Function converts a valid date and time expression to type date.
Syntax
cdate(date)
107
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
a = cdate("Jan 01 2020")
document.write("The Value of a : " & a)
document.write("<br />")
b = cdate("31 Dec 2050")
document.write("The Value of b : " & b)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
The Value of a : 1/01/2012
The Value of b : 31/12/2050
DateAdd Function
A Function, which returns a date to which a specified time interval has been added.
Syntax
DateAdd(interval,number,date)
Parameter Description
yyyy - year
w - weekday
108
VBScript
ww - week
q - quarter
h - hour
m - minute
s - second
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
VBScript
110
VBScript
DateDiff Function
It is a function that returns the difference between two specified time intervals.
Syntax
DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])
Parameter Description
yyyy - year
w - weekday
ww - week
q - quarter
h - hour
m - minute
s - second
firstdayofweek is Optional. Specifies the first day of the week. It can take the
following values:
o
1 = vbSunday - Sunday
2 = vbMonday - Monday
3 = vbTuesday - Tuesday
4 = vbWednesday - Wednesday
5 = vbThursday - Thursday
6 = vbFriday - Friday
111
VBScript
7 = vbSaturday - Saturday
firstdayofyear is Optional. Specifies the first day of the year. It can take the
following values:
o
2 = vbFirstFourDays - Start with the week that has at least four days in the
new year
3 = vbFirstFullWeek - Start with the first full week of the new year
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
fromDate="01-Jan-09 00:00:00"
toDate="01-Jan-10 23:59:00"
document.write("Line 1 : " &DateDiff("yyyy",fromDate,toDate) & "<br />")
document.write("Line 2 : " &DateDiff("q",fromDate,toDate) & "<br />")
document.write("Line 3 : " &DateDiff("m",fromDate,toDate) & "<br />")
document.write("Line 4 : " &DateDiff("y",fromDate,toDate) & "<br />")
document.write("Line 5 : " &DateDiff("d",fromDate,toDate) & "<br />")
document.write("Line 6 : " &DateDiff("w",fromDate,toDate) & "<br />")
document.write("Line 7 : " &DateDiff("ww",fromDate,toDate)& "<br />")
document.write("Line 8 : " &DateDiff("h",fromDate,toDate) & "<br />")
document.write("Line 9 : " &DateDiff("n",fromDate,toDate) & "<br />")
document.write("Line 10 : "&DateDiff("s",fromDate,toDate) & "<br />")
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : 1
Line 2 : 4
112
VBScript
Line 3 : 12
Line 4 : 365
Line 5 : 365
Line 6 : 52
Line 7 : 52
Line 8 : 8783
Line 9 : 527039
Line 10 : 31622340
DatePart Function
It is a function that returns the specific part of a given date.
Syntax
DatePart(interval,date[,firstdayofweek[,firstweekofyear]])
Parameter Description
yyyy - year
w - weekday
ww - week
q - quarter
h - hour
m - minute
s - second
firstdayofweek is Optional. Specifies the first day of the week. It can take the
following values:
113
VBScript
1 = vbSunday - Sunday
2 = vbMonday - Monday
3 = vbTuesday - Tuesday
4 = vbWednesday - Wednesday
5 = vbThursday - Thursday
6 = vbFriday - Friday
7 = vbSaturday - Saturday
firstdayofyear is Optional. Specifies the first day of the year. It can take the
following values:
o
2 = vbFirstFourDays - Start with the week that has at least four days in the
new year
3 = vbFirstFullWeek - Start with the first full week of the new year
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Date1 = "2013-01-15"
Quarter
= DatePart("q", Date1)
= DatePart("y", Date1)
VBScript
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : 1
Line 2 : 15
Line 3 : 3
Line 4 : 1
DateSerial Function
It is a function that returns a date for the specified day, month and year parameters.
Syntax
DateSerial(year,month,day)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
document.write(DateSerial(2013,5,10))
</script>
</body>
115
VBScript
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Fri May 10 00:00:00 UTC+0530 2013
FormatDateTime Function
It is a function that helps the developers to format and return a valid date and time
expression.
Syntax
FormatDateTime(date,format)
Parameter Description
format, an Optional Parameter. The Value that specifies the date or time format
to be used. It can take the following values:
o
o
o
o
o
0
1
2
3
4
=
=
=
=
=
vbGeneralDate - Default.
vbLongDate - Returns date.
vbShortDate - Returns date.
vbLongTime - Returns time.
vbShortTime - Returns time.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
d=("2013-08-15 20:25")
document.write("Line 1 : " & FormatDateTime(d) & " <br />")
document.write("Line 2 : " & FormatDateTime(d,1) & "<br />")
document.write("Line 3 : " & FormatDateTime(d,2) & "<br />")
document.write("Line 4 : " & FormatDateTime(d,3) & "<br />")
document.write("Line 5 : " & FormatDateTime(d,4) & "<br />")
</script>
116
VBScript
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : 15/08/2013 8:25:00 PM
Line 2 : Thursday, 15 August 2013
Line 3 : 15/08/2013
Line 4 : 8:25:00 PM
Line 5 : 20:25
IsDate Function
It is a function that returns a Boolean Value whether or Not the given input is a date.
Syntax
IsDate(expression)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : True
Line 2 : True
Line 3 : True
117
VBScript
Day Function
The Day function returns a number between 1 and 31 that represents the day of the
specified date.
Syntax
Day(date)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
document.write(Day("2013-06-30"))
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
30
Month Function
The Month function returns a number between 1 and 12 that represents the month of the
specified date.
Syntax
Month(date)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
118
VBScript
document.write(Month("2013-06-30"))
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
6
Year Function
The Year function returns an integer that represents a year of the specified date.
Syntax
Year(date)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
document.write(Year("2013-06-30"))
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
2013
MonthName Function
The MonthName function returns the name of the month for the specified date.
Syntax
119
VBScript
MonthName(month[,toabbreviate])
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : Jan
Line 2 : January
Line 3 : Jul
Line 4 : July
WeekDay Function
The WeekDay function returns an integer from 1 to 7 that represents the day of the week
for the specified date.
Syntax
Weekday(date[,firstdayofweek])
120
VBScript
Parameter Description
Date, a Required Parameter. The Week day would be returns for this specified
date.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: 5
Line 2: 4
Line 3: 4
Line 4: 3
Line 5: 4
121
VBScript
Line 6: 5
WeekDayName Function
The WeekDayName function returns the name of the Weekday for the specified day.
Syntax
WeekdayName(weekday[,abbreviate[,firstdayofweek]])
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
122
VBScript
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1 : Tuesday
Line 2 : Mon
Line 3 : Sunday
Line 4 : Tue
Line 5 : Sunday
Time Functions
Function
Description
Now
Hour
Minute
Second
Time
Timer
TimeSerial
A Function that returns the time for the specific input of hour, minute
and second
TimeValue
Now Function
The Function Now returns the current system date and time.
Syntax
123
VBScript
Now()
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
a = Now()
document.write("The Value of a : " & a)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
The Value of a : 19/07/2013 3:04:09 PM
Hour Function
The Hour Function returns a number between 0 and 23 that represents the hour of the
day for the specified time stamp.
Syntax
Hour(time)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
124
VBScript
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: 15
Line 2: 23
Line 3: 14
Minute Function
The Minute Function returns a number between 0 and 59 that represents the Minute of the
hour for the specified time stamp.
Syntax
Minute(time)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: 13
Line 2: 43
Line 3: 20
125
VBScript
Second Function
The Second Function returns a number between 0 and 59 that represents the Second of
the hour for the specified time stamp.
Syntax
Second(time)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: 25
Line 2: 45
Line 3: 0
Time Function
The Time Function returns the current system time.
Syntax
Time()
Example
<!DOCTYPE html>
<html>
126
VBScript
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Line 1: 3:29:15 PM
Timer Function
The Timer Function returns the number of seconds and milliseconds since 12:00 AM.
Syntax
Timer()
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
Time is : 19/07/2013 3:45:53 PM
Timer is: 56753.4
127
VBScript
TimeSerial Function
The TimeSerial function returns the time for the specified hour, minute and second values.
Syntax
TimeSerial(hour,minute,second)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
8:01:02 PM
12:59:59 AM
2:20:18 PM
TimeValue Function
The TimeValue Function converts the given input string to a valid time.
128
VBScript
Syntax
TimeValue(StringTime)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will
produce the following result:
8:30:00 PM
5:15:00 AM
2:30:58 AM
129
VBScript
130
16. PROCEDURES
VBScript
What is a Function?
A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing same code over and over again. This will enable
programmers to divide a big program into a number of small and manageable functions.
Apart from inbuilt Functions, VBScript allows us to write user-defined functions as well.
This section will explain you how to write your own functions in VBScript.
Function Definition
Before we use a function, we need to define that particular function. The most common
way to define a function in VBScript is by using the Function keyword, followed by a
unique function name and it may or may not carry a list of parameters and a statement
with an End Function keyword, which indicates the end of the function. The basic syntax
is shown below:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Function Functionname(parameter-list)
statement 1
statement 2
statement 3
.......
statement n
End Function
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
131
VBScript
Function sayHello()
msgbox("Hello there")
End Function
</script>
</body>
</html>
Calling a Function
To invoke a function somewhere later in the script, you would simple need to write the
name of that function with the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Function sayHello()
msgbox("Hello there")
End Function
Call sayHello()
</script>
</body>
</html>
Function Parameters
Till now, we have seen function without a parameter, but there is a facility to pass different
parameters while calling a function. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. The Functions are
called using the Call Keyword.
<!DOCTYPE html>
<html>
132
VBScript
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
Example
This function takes two parameters and concatenates them and returns result in the calling
program. In VBScript, the values are returned from a function using function name. In
case if you want to return two or more values, then the function name is returned with an
array of values. In the calling program, the result is stored in the result variable.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
End Function
</script>
</body>
133
VBScript
</html>
Now, we can call this function as follows:
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Function concatenate(first, last)
Dim full
full = first & last
concatenate = full
End Function
' Here is the usage of returning value from function.
dim result
result = concatenate("Zara", "Ali")
msgbox(result)
</script>
</body>
</html>
Sub-Procedures
Sub-Procedures are similar to functions but there are few differences.
Sub-procedures DONOT Return a value while functions may or may not return a
value.
Sub-procedures are always enclosed within Sub and End Sub statements.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub
134
VBScript
</script>
</body>
</html>
Calling Procedures
To invoke a Procedure somewhere later in the script, you would simply need to write the
name of that procedure with or without the Call keyword.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Sub sayHello()
msgbox("Hello there")
End Sub
sayHello()
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
135
VBScript
<body>
<script language="vbscript" type="text/vbscript">
Dim x,y
x=6
y=4
res= fnadd(x,y)
document.write("The value of x is " & x & "<br />")
document.write("The value of y is " & y & "<br />")
</script>
</body>
</html>
The above function takes the parameter x and y as by values. Hence, after executing the
function, the values are unchanged.
If the above function is saved as .html and executed in IE, the output would be as follows:
The value of x is 6
The value of y is 4
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
VBScript
num1 = 4
num2 = 5
End Function
Dim x,y
x=6
y=4
res= fnadd(x,y)
document.write("The value of x is " & x & "<br />")
document.write("The value of y is " & y & "<br />")
</script>
</body>
</html>
The above function takes the parameter x and y as by reference. Hence, after executing
the function, the values are changed.
If the above function is saved as .html and executed in IE, the output would be as follows:
The value of x is 4
The value of y is 5
137
VBScript
Syntax
MsgBox(prompt[,buttons][,title][,helpfile,context])
Parameter Description
Title - An Optional Parameter. A String expression displayed in the title bar of the
dialog box. If the title is left blank, the application name is placed in the title bar.
helpfile - An Optional Parameter. A String expression that identifies the Help file
to use to provide context-sensitive help for the dialog box.
VBScript
0 vbApplicationModal Application modal. The current application will not work until
the user responds to the message box.
4096 vbSystemModal System modal. All applications will not work until the user
responds to the message box.
The above values are logically divided into four groups: The first group(0 to 5) indicates
the buttons to be displayed in the message box. The second group (16, 32, 48, 64)
describes the sytle of the icon to be displayed, the third group (0, 256, 512, 768) indicates
which button must be the default, and the fourth group (0, 4096) determines the modality
of the message box.
Return Values
The MsgBox function can return one of the following values:
139
VBScript
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
When the above script is executed, the message box is displayed, and if you press No
Button, then the value of a is 7.
The Value of a is 7
Syntax
InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
Parameter Description
140
VBScript
Title - An Optional Parameter. A String expression displayed in the title bar of the
dialog box. If the title is left blank, the application name is placed in the title bar.
Default - An Optional Parameter. A default text in the text box that the user would
like to be displayed.
XPos - An Optional Parameter. The Position of X axis which represents the prompt
distance from left side of the screen horizontally. If left blank, the input box is
horizontally centered.
YPos - An Optional Parameter. The Position of Y axis which represents the prompt
distance from left side of the screen Vertically. If left blank, the input box is
Vertically centered.
helpfile - An Optional Parameter. A String expression that identifies the Help file
to use to provide context-sensitive Help for the dialog box.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
141
VBScript
</script>
</body>
</html>
When the above script is executed, the input box is displayed and displays the entered
value by the user.
142
VBScript
What is an Object?
VBScript runtime objects help us to accomplish various tasks. This section will help you
understand how to instantiate an object and work with it.
Syntax
In order to work with objects seamlessly, we need to declare the object and instantiate it
using Set Keyword.
Dim objectname
Example
In the below example, we are creating an object of type Scripting.Dictionary.
Dim obj
Set obj = CreateObject("Scripting.Dictionary")
Syntax
In order to destroy the objects, we need to use Set Keyword followed by the object name
and point it to Nothing.
Set objectname = Nothing 'Destroy the object.
Example
In the below example, we are creating an object of type Scripting.Dictionary.
Dim obj
Set obj = CreateObject("Scripting.Dictionary")
Set obj = Nothing.
143
VBScript
Object Usage
Please click on each one of the given object types to know more.
Object Type
Description
Class
Scripting.FileSystemObject
Scripting.Dictionary
Debug
Class Objects
Class is a construct that is used to define a unique type. Like Object Oriented
Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing
COM objects with VB.
Class is simply the template for an object and we instantiate an object to access the
properties and methods of it. Classes can contain variables, properties, methods or events.
Syntax
VBScript classes are enclosed within Class .... End Class
'Defining the Class
Class classname
...
End Class
Class Variables
Classes can contain variables, which can be of private or public. Variables within classes
should follow VBScript naming conventions. By default, the variables in class are Public.
That is why they can be accessed outside the class.
144
VBScript
Class Properties
Class properties, such as Property Let, which handles the process of data validation and
assigning the new value to the private variable. Property set, which assigns the new
property value to the private object variable.
Read-only properties have only a Property Get procedure while write-only properties
(which are rare) have only a Property Let or a Property Set procedure.
Example
In the below example, we are using Properties to wrap private variables.
Class Comp
Private modStrType
Private OS
End Class
145
VBScript
Class Methods
Methods allow the class to perform the operation that the developer wants. The Methods
are nothing but Functions or Subroutines.
Example
In the below example, we are using Properties to wrap private variables.
Class Car
Private Model
Private Year
Public Start()
Fuel = 2.45
Pressure =
4.15
End Function
End Class
Class Events
There are two events that are automatically associated with every class by default.
Class_Initialize and Class_Terminate.
Class_Initialize is triggered whenever you instantiate an object based on the class.
Class_Terminate event is fired when the object goes out of scope or when the object is
set to Nothing.
Example
In the below example, we will make you understand how the events work in VBScript.
'Instantation of the Object
Set objectname = New classname
VBScript
End Sub
FileSystem Objects
As the name suggests, FSO Objects help the developers to work with drives, folders and
files. In this section, we will discuss:
Description
Drive
Drives
File
Files
Folder
Folders
TextStream
Drive
Drive is an object, which provides access to the properties of a particular disk drive or
network share. The Following properties are supported by Driveobject:
AvailableSpace
DriveLetter
DriveType
FileSystem
147
VBScript
FreeSpace
IsReady
Path
RootFolder
SerialNumber
ShareName
TotalSize
VolumeName
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
& "
"
</script>
</body>
</html>
If the above script is saved as HTML and executed in IE, we would get the following output
in the console.
Drive - Win 7 Free Space:20,154,059 Kbytes
148
VBScript
Drives
Drives is a collection, which provides details of all the drives attached to the system,
either physically or logically. It carries two properties:
Count Property
Item Property
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
document.write s
document.write dc.count
</script>
</body>
</html>
If the above script is saved as HTML and executed in IE, we would get the following output
in the console.
149
VBScript
File
File is an Object, which contains both properties and methods that allow the developers
to create, delete or move a file.
Methods
Copy
Delete
Move
openasTextStream
Properties
Attributes
DateCreated
DateLastAccessed
DateLastModified
Drive
Name
ParentFolder
Path
ShortName
ShortPath
Size
Type
Example
<!DOCTYPE html>
<html>
<body>
150
VBScript
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("C:\user.js")
document.write "Line 1: "& f.DateCreated & "<br />"
document.write "Line 2: "& f.Attributes & "<br />"
document.write "Line 3: "& f.DateLastAccessed & "<br />"
document.write "Line 4: "& f.DateLastModified & "<br />"
document.write "Line 5: "& f.Drive
document.write "Line 6: "& f.Name
</script>
</body>
</html>
If the above script is saved as HTML and executed in IE, we would get the following output
in the console.
Line 1: 08/02/13 06:57:34
Line 2: 32
Line 3: 08/02/13 06:57:34
Line 4: 04/18/12 22:23:37
Line 5: C:
Line 6: user.js
Line 7: C:\
Line 8: C:\user.js
Line 9: user.js
Line 10: C:\user.js
151
VBScript
Files
Files is a collection, which provides a list of all files contained within a folder.
Properties
Count
Item
Example
<!DOCTYPE html>
<html>
<body>
<scrip
t language="vbscript" type="text/vbscript">
'Get Item
Set s = fc.Item("sendmail.vbs")
'Get Count
x = fc.Count
Document.write s
Document.write x
</script>
</body>
</html>
152
VBScript
If the above script is saved as HTML and executed in IE, we would get the following output
in the console.
D:\PROJECT\sendmail.vbs
6
Folder
Folder is an Object, which contains both properties and methods that allow the developers
to create, delete or move a folder.
Methods
Copy
Delete
Move
CreateTextFile
Properties
Attributes
DateCreated
DateLastAccessed
DateLastModified
Drive
Files
IsRootFolder
Name
ParentFolder
Path
ShortName
ShortPath
Size
SubFolders
153
VBScript
Type
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
&f.IsRootFolder
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
154
VBScript
ShowFileInfo =
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
ShowFileInfo =
"ShortPath : "
& f.ShortPath
document.write ShowFileInfo
ShowFileInfo =
document.write ShowFileInfo
f.Type
document.write ShowFileInfo
</script>
</body>
</html>
If the above script is saved as HTML and executed in IE, we would get the following output
in the console.
Created: 22/02/2012 8:24:57 PM
attributes 16
Last Accessed : 1/08/2013 12:48:36 PM
DateLastModified : 1/08/2013 12:48:36 PM
Drive : D:
count : 6
IsRoot folder : False
Name : PROJECT
parent folder : D:\
Path : D:\PROJECT
shortname : PROJECT
ShortPath : D:\PROJECT
155
VBScript
Folders
Folders is an collection of all Folder Objects within a Folder object.
Methods
Add
Properties
Count
Item
Example
If the above script is saved as HTML and executed in IE, we would create a folder with
name "Test_Folder".
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
156
VBScript
TextStream
TextStream object helps the developers to work with text files seamlessly. Developers
can read, write or append the contents to the text file using the text stream object.
Syntax
TextStream.{property
| method( )}
Example
If the above script is saved as HTML and executed in IE, we would create a folder with
name "Test_Folder".
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTextFile
Set objTextFile = objFSO.CreateTextFile("D:\Testfile.txt")
objTextFile.Close
Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile("D:\Testfile.txt",ForAppending,True)
objTextFile.WriteLine "Welcome to VBScript Programming"
objTextFile.Close
Set objTextFile = Nothing
Set objFSO = Nothing
</script>
</body>
</html>
If the above script is saved as HTML and executed in IE, it will create a text file in D:\
Drive and append the string specified in the WriteLine Method.
Welcome to VBScript Programming
157
VBScript
Dictionary Objects
A Dictionary object can be compared to a PERL associative array. Any Values can be stored
in the array and each item is associated with a unique key. The key is used to retrieve an
individual element and it is usually an integer or a string, but can be anything except an
array.
Syntax
VBScript classes are enclosed within Class .... End Class.
Dim variablename
Set variablename = CreateObject("Scripting.Dictionary")
variablename.Add (key, item)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim obj_datadict
</script>
</body>
</html>
There are various methods associated with DataDictionary Objects which enable the
developers to work with dictionary objects seamlessly.
Exists Method
Exist Method helps the user to check whether or not the Key Value pair exists.
object.Exists(key)
Parameter Description
Object, a Mandatory Parameter. This represents the name of the Dictionary Object.
158
VBScript
Key, a Mandatory Parameter. This represents the value of the Dictionary Object.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim d, msg
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Apple"
Else
msgbox
End If
</script>
</body>
</html>
Save the file as .HTML, and upon executing the above script in IE, it displays the following
message in a message box.
Specified key exists.
Items Method
Items Method helps us to get the values stored in the key value pair of the data dictionary
object.
Parameter Description
Object, a Mandatory Parameter. This represents the name of the Dictionary Object.
Example
<!DOCTYPE html>
159
VBScript
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim obj_datadict
msgbox a(0)
msgbox a(2)
</script>
</body>
</html>
Save the file as .HTML, and upon executing the above script in IE, it displays the following
message in a message box.
Apple
C++
Keys Method
object.Keys( )
Parameter Description
Object, a Mandatory Parameter. This represents the name of the Dictionary Object.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim obj_datadict
VBScript
msgbox a(0)
msgbox a(2)
</script>
</body>
</html>
Save the file as .HTML, and upon executing the above script in IE, it displays the following
message in a message box.
a
c
Remove Method
object.Remove(key)
Parameter Description
Object, a Mandatory Parameter. This represents the name of the Dictionary Object.
Key, a Mandatory Parameter. This represents the key value pair that needs to be
removed from the Dictionary Object.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim obj_datadict
VBScript
msgbox a(0)
msgbox a(2)
obj_datadict.remove("b")
</script>
</body>
</html>
Save the file as .HTML, and upon executing the above script in IE, it displays the following
message in a message box.
a
c
Parameter Description
Object, a Mandatory Parameter. This represents the name of the Dictionary Object.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim obj_datadict
162
VBScript
msgbox a(0)
msgbox a(2)
obj_datadict.removeall
</script>
</body>
</html>
Debug Objects
The Debug Objects are global objects that can send output to a script debugger. Here, the
debugger what we refer to is Microsoft Script Debugger.
The Debug objects cannot be created like other objects but can be used when we are
debugging.
The following methods are supported by Debug Objects. These methods or objects have
no effect if the script is NOT executed in debug mode. The Methods supported by Debug
Objects are discussed in detail.
Write
The Write method sends strings to the immediate window of the Microsoft Script Debugger
at run-time. If the script is not executed in debug mode, then the Write method has no
effect.
Write Debug.Write([str1 [, str2 [, ... [, strN]]]])
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim counter
counter = 42
Debug.Write "The value of counter is " & counter
</script>
</body>
163
VBScript
</html>
WriteLine
The Writeline method is very similar to Write method. The WriteLine method sends strings,
followed by a newline character, to the immediate window of the Microsoft Script Debugger
at run time. If the script is not executed in debug mode, then the WriteLine method has
no effect.
Debug.WriteLine([str1 [, str2 [, ... [, strN]]]])
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim counter
counter = 42
Debug.WriteLine "The value of counter is " & counter
</script>
</body>
</html>
In the Browsing category, clear the Disable script debugging check box.
Click OK.
164
VBScript
RegExp Object
RegExp object helps the developers to match the pattern of strings and the properties and
methods help us to work with Regular Expressions easily. It is similar to RegExp in
JavaScript
Properties
Pattern - The Pattern method represents a string that is used to define the regular
expression and it should be set before using the regular expression object.
Methods
Test (search-string) - The Test method takes a string as its argument and returns
True if the regular expression can successfully be matched against the string,
otherwise False is returned.
Execute (search-string) - The Execute method works like Replace, except that it
returns a Matches collection object, containing a Match object for each successful
match. It doesn't modify the original string.
VBScript
Count - The Count method represents the number of match objects in the
collection.
Item - The Item method enables the match objects to be accessed from matches
collections object.
Match Object
The Match object is contained within the matches collection object. These objects
represent the successful match after the search for a string.
FirstIndex - It represents the position within the original string where the match
occurred. This index are zero-based which means that the first position in a string
is 0.
Length - A value that represents the total length of the matched string.
Value - A value that represents the matched value or text. It is also the default
value when accessing the Match object.
Position Matching
The significance of position matching is to ensure that we place the regular expressions at
the correct places.
Symbol
Description
\b
\B
Literals Matching
Any form of characters such as alphabet, number or special character or even decimal,
hexadecimal can be treated as a Literal. Since few of the characters have already got a
special meaning within the context of Regular Expression, we need to escape them using
escape sequences.
166
VBScript
Symbol
Alphanumeric
Description
Matches alphabetical and numerical characters only.
\n
\[
\]
\(
\)
\t
\v
\|
\{
\}
\\
\?
\*
\+
\.
\b
\B
\f
167
VBScript
\r
\xxx
\xdd
\uxxxx
Description
Match any of the character class enclosed within the character set.
Matches any of the character class that are NOT enclosed within the
character set.
Matches any character class except \n
\w
\W
\d
\D
\s
\S
Repetition Matching
Repetition matching allows multiple searches within the regular expression. It also
specifies the number of times an element is repeated in a Regular Expression.
168
VBScript
Symbol
Description
{x}
{x,}
{x,y}
Description
Description
"((\$\s?)|(#\s?))?"
169
VBScript
"((\d+(\.(\d\d)?)?))"
Example
The below example checks whether or not the user entered an email id whose format
should match such that there is an email id followed by '@' and then followed by domain
name.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
strid = "[email protected]"
Set re = New RegExp
With re
.Pattern
= "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"
.IgnoreCase = False
.Global
= False
End With
Set re = Nothing
</script>
</body>
</html>
170
VBScript
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors,
and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For
example, the following line causes a syntax error because it is missing a closing
parenthesis:
<script type="text/vbscript">
dim x,y
x = "Tutorialspoint"
y = Ucase(x
</script>
Runtime Errors
Runtime errors, also called exceptions, occur during execution, after interpretation. For
example, the following line causes a runtime error because here syntax is correct but at
runtime it is trying to call fnmultiply, which is a non-existing function:
<script type="text/vbscript">
Dim x,y
x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
Function fnadd(x,y)
fnadd = x+y
End Function
</script>
171
VBScript
Logical errors
Logic errors can be the most difficult type of errors to track down. These errors are not
the result of a syntax or runtime error. Instead, they occur when you make a mistake in
the logic that drives your script and you do not get the result you expected. You cannot
catch those errors, because it depends on your business requirement what type of logic
you want to put in your program. For example, dividing a number by zero or a script that
is written which enters into infinite loop.
Err Object
Assume if we have a runtime error, then the execution stops by displaying the error
message. As a developer, if we want to capture the error, then Error Object is used.
Example
In the following example, Err.Number gives the error number and Err.Description gives
error description.
<script type="text/vbscript">
Err.Raise 6
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear
</script>
172
VBScript
VBScript has a few other important statements to help developers develop an efficient
script. The following table lists a set of such important statements. In this chapter, we will
discuss each of these statements in detail with examples.
Category
Options
Option Explicit
Script Engine ID
ScriptEngine
variants
Expression
Eval,Execute
Control Statement
With...End With
Math Function
Randomize
Option Explicit
Option Explicit forces the developer to declare the variables using Dim statement before
they are used in some part of the code.
Syntax
Option Explicit
Example
If we use Option Explicit and if we don't declare the variables then the interpreter will
throw and error.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Option Explicit
173
VBScript
Dim x,y,z,a
x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
Function fnadd(x,y)
fnadd = x+y
End Function
</script>
</body>
</html>
ScriptEngine
ScriptEngine represents the details of the scripting language in use. It is also used in
combination
with
ScriptEngineMajorVersion,
ScriptEngineMinor
Version,
ScriptEngineBuildVersion which gives the major version of the vbscript engine, minor
version the vbscript engine, and the build version of vbscript respectively.
Syntax
ScriptEngine
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim scriptdetails
scriptdetails =
VBScript
Document.write scriptdetails
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE , the following result is
displayed on the screen.
Version VBScript - 5.8.16996
IsEmpty
The Function IsEmpty is used to check whether or not the expression is empty. It returns
a Boolean value. IsEmpty returns True if the variable is uninitialized or explicitly set to
Empty. Otherwise the expression returns False.
Syntax
IsEmpty(expression)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var = Null
MyCheck = IsEmpty(var)
Document.write "Line 2 : " & MyCheck & "<br />"
var = Empty
VBScript
MyCheck = IsEmpty(var)
Document.write "Line 3 : " & MyCheck & "<br />"
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
Line 1 : True
Line 2 : False
Line 3 : True
IsNull
The Function IsNull is used to check whether or not the expression has a valid data. It
returns a Boolean value. IsNull returns True if the variable is Null otherwise the expression
returns False.
Syntax
IsNull(expression)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
var = Null
res = IsNull(var)
document.write "Line 2 : " & res & "<br />"
var = Empty
res = IsNull(var)
176
VBScript
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
Line 1 : False
Line 2 : True
Line 3 : False
IsObject
The IsObject Function is used to check whether or not the expression has a valid Object.
It returns a Boolean value. IsObject returns True if the expression contains an object
subtype otherwise the expression returns False.
Syntax
IsObject(expression)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim fso,b
b = 10
set fso = createobject("Scripting.Filesystemobject")
x = isobject(fso)
Document.write "Line 1 : " &
y = isobject(b)
Document.write "Line 2 : " &
</script>
</body>
</html>
177
VBScript
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
Line 1 : True
Line 2 : False
IsNumeric
The IsNumeric Function is used to check whether or not the expression has a number
subtype. It returns a Boolean value. IsObject returns True if the expression contains an
number subtype otherwise the expression returns False.
Syntax
IsNumeric(expression)
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
chk
chk
var = "3.1415935745"
chk = IsNumeric(var)
Document.write "Line 2 : " &
chk
</script>
</body>
</html>
178
VBScript
Save the file with .html extension upon executing the script in IE , the following result is
displayed on the screen.
Line 1 : True
Line 2 : True
Line 3 : False
TypeName
The TypeName Function is used to return the variant subtype information of the variable.
Syntax
TypeName(varname)
The Typename function can return any of the following values.
Error
Example
<!DOCTYPE html>
179
VBScript
<html>
<body>
<script language="vbscript" type="text/vbscript">
vartype = TypeName(3.1450)
Document.write "Line 1 : " &
vartype
vartype
vartype = TypeName(432)
Document.write "Line 2 : " &
vartype = TypeName("Microsoft")
Document.write "Line 3 : " &
vartype
vartype
vartype
vartype = TypeName(NullVar)
Document.write "Line 4 : " &
vartype = TypeName(ArrVar)
Document.write "Line 5 : " &
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
Line 1 : Double
Line 2 : Integer
Line 3 : String
Line 4 : Null
Line 5 : Variant()
Eval
The Eval Function executes an expression and returns the result either as a string or a
number.
Syntax
180
VBScript
Eval(expression)
The argument Expression can be a string expression or a number. If you pass to the Eval
function a string that doesn't contain a numeric expression or a function name but only a
simple text string, a run-time error occurs. For example, Eval("VBScript") results in an
error.
Example
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
20
false
15
Execute
The Execute statement accepts argument that is a string expression containing one or
more statements for execution.
Syntax
Execute(expression)
In VBScript, a = b can be interpreted two ways. It can be treated as an assignment
statement where the value of x is assigned to y. It can also be interpreted as an expression
that tests if a and b have the same value. If they do, result is True; if they are not, result
is False. The Execute statement always uses the first interpretation while the Eval
statement always uses the second.
Example
181
VBScript
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Dim x
x = "Global"
y = "VBScript"
Execute("x=y")
msgbox x
msgbox y
</script>
</body>
</html>
Save the file with .html extension upon executing the script in IE, the following result is
displayed on the screen.
VBScript
VBScript
With..End With
The With statement allows us to perform a series of operation on a specified object without
explicitly mentioning the object name over again and again.
Syntax
With (objectname)
statement 1
statement 2
statement 3
...
...
statement n
End With
Example
182
VBScript
Upon Executing the following script, Winword gets opened and the specified text is
entered.
<!DOCTYPE html>
<html>
<body>
<script language="vbscript" type="text/vbscript">
Msg =
' Objects methods are accessed without requaliyfying the objects again.'
With objWord
.Documents.Add
.Selection.TypeText Msg
.Selection.WholeStory
End With
</script>
</body>
</html>
Randomize
The Randomize statement initializes the random number generator which is helpful for the
developers to generate a random number.
Syntax
Randomize [number]
Example
Upon Executing the following script, Winword gets opened and the specified text is
entered.
<!DOCTYPE html>
<html>
<body>
183
VBScript
Dim MyValue
Randomize
MyValue = Int((100 * Rnd) + 1)
MsgBox MyValue
</script>
</body>
</html>
Save the above script as HTML and upon executing the script in IE, the following output is
shown.
42
184