Vbscript Tutorial
Vbscript Tutorial
Vbscript Tutorial
SAMPAT PATNAIK
MPX TECHNOLOGIES
VBSCRIPT
COMPLETE REFERENCE
SAMPAT PATNAIK
INSTRUCTOR
MPX TECHNOLOGIES
http://mpxbezone.com
1
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
CHAPTER 1
INTRODUCTION
WHAT IS VBSCRIPT?
When a VBScript is inserted into an HTML document, the Internet browser will read
the HTML and interpret the VBScript. The VBScript can be executed immediately, or at a
later event.
To insert a VBScript into an HTML page, we use the <script> tag. Inside the <script>
tag we use the type attribute to define the scripting language.
So, the <script type="text/vbscript"> and </script> tells where the VBScript starts
and ends:
<html>
<body>
<script type="text/vbscript">
...
</script>
</body>
</html>
The example below shows how to display text and add HTML tags to the VBScript:
<html>
<body>
<script type="text/vbscript">
document.write("<h1>Hello World!</h1>")
</script>
</body></html>
2
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
Browsers that do not support VBScript, will display VBScript as page content.To
prevent them from doing this, the HTML comment tag should be used to "hide" the
VBScript.Just add an HTML comment tag <!-- before the first VBScript statement, and a -->
(end of comment) after the last VBScript statement, like this:
<html>
<body>
<script type="text/vbscript">
<!--
document.write("Hello World!")
-->
</script>
</body>
</html>
VBScripts in the body section will be executed WHILE the page loads.VBScripts in
the head section will be executed when CALLED.
VBScripts in a page will be executed immediately while the page loads into the
browser. This is not always what we want. Sometimes we want to execute a script when a
page loads, other times when a user triggers an event.
SCRIPTS IN <HEAD>
Scripts to be executed when they are called, or when an event is triggered, go in the
head section. If you place a script in the head section, you will ensure that the script is
loaded before anyone uses it.
<html>
<head>
<script type="text/vbscript">
alert("Hello World!")
</script>
</head>
3
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<body>
</body>
</html>
SCRIPTS IN <BODY>
Scripts to be executed when the page loads go in the body section.If you place a script in the
body section, it generates the content of a page.
<html>
<head>
</head>
<body>
<script type="text/vbscript">
document.write("This message is written by VBScript")
</script>
</body>
</html>
You can place an unlimited number of scripts in your document, so you can have
scripts in both the body and the head section.
<html>
<head>
<script type="text/vbscript">....</script>
</head>
<body>
<script type="text/vbscript">....</script>
</body>
</html>
VBSCRIPT VARIABLES
4
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
In VBScript, all variables are of type variant, that can store different types of data.
You can declare VBScript variables with the Dim, Public or the Private statement. Like this:
dim x;
dim firstname;
Now you have created two variables. The name of the variables are "x" and
"firstname". You can also declare variables by using its name in a script. Like this:
firstname=”sampat”
Now you have also created a variable. The name of the variable is "firstname".
However, this method is not a good practice, because you can misspell the variable name
later in your script, and that can cause strange results when your script is running.
If you misspell for example the "firstname" variable to "firstnime", the script will
automatically create a new variable called "firstnime". To prevent your script from doing
this, you can use the Option Explicit statement. This statement forces you to declare all
your variables with the dim, public or private statement.
Put the Option Explicit statement on the top of your script. Like this:
option explicit
dim firstname
firstname=some value
firstname="sampat"
x=10
The variable name is on the left side of the expression and the value you want to
assign to the variable is on the right. Now the variable "firstname" has the value of "sampat",
and the variable "x" has the value of "10".
5
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
LIFETIME OF VARIABLES
When you declare a variable within a procedure, the variable can only be accessed
within that procedure. When the procedure exits, the variable is destroyed. These variables
are called local variables. You can have local variables with the same name in different
procedures, because each is recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures on your page can
access it. The lifetime of these variables starts when they are declared, and ends when the
page is closed.
An array variable is used to store multiple values in a single variable.In the following
example, an array containing 3 elements is declared:
dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3
elements. This is a fixed-size array. You assign data to each of the elements of the array like
this:
names(0)="sampat"
names(1)="satrupa"
names(2)="Santosh"
Similarly, the data can be retrieved from any element using the index of the
particular array element you want. Like this:
tutor=names(0)
dim table(4,6)
6
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
CHAPTER 2
VBSCRIPT PROCEDURES
Sub procedure
Function procedure
A Sub procedure:
Sub mysub()
some statements
End Sub
or
Sub mysub(argument1,argument2)
some statements
End Sub
A Function procedure:
Function myfunction()
some statements
myfunction=some value
End Function
7
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function
<html>
<body>
<script type="text/vbscript">
randomize()
r=rnd()
if r>0.5 then
document.write("<a href='http://www.w3schools.com'>Learn Web
Development!</a>")
else
document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes
Data!</a>")
end if
</script>
<p>This example demonstrates a link, when you click on the link it will take
you to W3Schools.com OR to RefsnesData.no. There is a 50% chance for each
of them.</p>
</body>
</html>
carname=findname()
Here you call a Function called "findname", the Function returns a value that will be
stored in the variable "carname".
Here you also call a Function called "findname", the Function returns a value that
will be displayed in the message box.When you call a Sub procedure you can use the Call
statement, like this:
8
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
Call MyProc(argument)
MyProc argument
9
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
CHAPTER 3
CONDITIONAL STATEMENTS
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:
if...then...else
If you want to execute only one statement when a condition is true, you can write
the code on one line:
There is no ..else.. in this syntax. You just tell the code to perform one action if a
condition is true (in this case if i=10).
If you want to execute more than one statement when a condition is true, you must
put each statement on separate lines, and end the statement with the keyword "end if":
if i=10 then
msgbox "Hello"
i = i+1
end if
There is no ..else.. in the example above either. You just tell the code to perform
multiple actions if the condition is true.
If you want to execute a statement if a condition is true and execute another statement if the
condition is not true, you must add the "else" keyword:
<html>
<body>
10
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<script type="text/vbscript">
function greeting()
i=hour(time)
if i < 10 then
document.write("Good morning!")
else
document.write("Have a nice day!")
end if
end function
</script>
</head>
<body onload="greeting()">
</body>
</html>
In the example above, the first block of code will be executed if the condition is true, and the other
block will be executed otherwise (if i is greater than 10).
if...then...elseif
You can use the if...then...elseif statement if you want to select one of many blocks of
code to execute:
<html>
<body>
<script type="text/vbscript">
function greeting()
i=hour(time)
if i = 10 then
document.write("Just started...!")
elseif i = 11 then
document.write("Hungry!")
elseif i = 12 then
document.write("Ah, lunch-time!")
elseif i = 16 then
document.write("Time to go home!")
else
document.write("Unknown")
end if
end function
</script>
</head>
11
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<body onload="greeting()">
</body>
</html>
SELECT CASE
You can also use the "select case" statement if you want to select one of many blocks
of code to execute:
<html>
<body>
<script type="text/vbscript">
d=weekday(date)
select case d
case 1
document.write("Sleepy Sunday")
case 2
document.write("Monday again!")
case 3
document.write("Just Tuesday!")
case 4
document.write("Wednesday!")
case 5
document.write("Thursday...")
case 6
document.write("Finally Friday!")
case else
document.write("Super Saturday!!!!")
end select
</script>
</body>
First we have a single expression (most often a variable), that is evaluated once. The
value of the expression is then compared with the values for each Case in the structure. If
there is a match, the block of code associated with that Case is executed.
12
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
CHAPTER 4
LOOPING STATEMENTS
Looping statements are used to run the same block of code a specified number of
times. In VBScript we have four looping statements:
FOR...NEXT LOOP
Use the For...Next statement to run a block of code a specified number of times.The
For statement specifies the counter variable (i), and its start and end values. The Next
statement increases the counter variable (i) by one.
<html>
<body>
<script type="text/vbscript">
for i = 0 to 5
document.write("The number is " & i & "<br />")
next
</script>
</body>
</html>
<html>
<body>
<script type="text/vbscript">
for i=1 to 6
document.write("<h" & i & ">This is header " & i & "</h" & i & ">")
next
</script>
</body>
</html>
13
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
With the Step keyword, you can increase or decrease the counter variable by the
value you specify. In the example below, the counter variable (i) is INCREASED by two, each
time the loop repeats.
To decrease the counter variable, you must use a negative Step value. You must
specify an end value that is less than the start value. In the example below, the counter
variable (i) is DECREASED by two, each time the loop repeats.
EXIT A FOR...NEXT
You can exit a For...Next statement with the Exit For keyword.
A For Each...Next loop repeats a block of code for each item in a collection, or for
each element of an array.
<html>
<body>
<script type="text/vbscript">
dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
for each x in cars
document.write(x & "<br />")
next
</script>
</body>
</html>
14
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
DO...LOOP
If you don't know how many repetitions you want, use a Do...Loop statement.The
Do...Loop statement repeats a block of code while a condition is true, or until a condition
becomes true.
Do While i>10
some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
some code
Loop While i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Do Until i=10
some code
Loop
If i equals 10, the code inside the loop will never be executed.
Do
some code
Loop Until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...Loop
Do Until i=10
15
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
i=i-1
If i<10 Then Exit Do
Loop
The code inside this loop will be executed as long as i is different from 10, and as
long as i is greater than 10.
16
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
CHAPTER 5
VBSCRIPT FUNCTIONS
Date/Time Functions
Function Description
CDate Converts a valid date and time expression to the variant of subtype Date
Date Returns the current system date
DateAdd Returns a date to which a specified time interval has been added
DateDiff Returns the number of intervals between two dates
DatePart Returns the specified part of a given date
DateSerial Returns the date for a specified year, month, and day
DateValue Returns a date
Day Returns a number that represents the day of the month (between 1 and 31, inclusive)
FormatDateTime Returns an expression formatted as a date or time
Hour Returns a number that represents the hour of the day (between 0 and 23, inclusive)
IsDate Returns a Boolean value that indicates if the evaluated expression can be converted to
a date
Minute Returns a number that represents minute of the hour (between 0 and 59, inclusive)
Month Returns a number that represents the month of the year (between 1 and 12, inclusive)
MonthName Returns the name of a specified month
Now Returns the current system date and time
Second Returns a number that represents second of the minute (between 0 and 59, inclusive)
Time Returns the current system time
Timer Returns the number of seconds since 12:00 AM
TimeSerial Returns the time for a specific hour, minute, and second
TimeValue Returns a time
Weekday Returns a number that represents the day of the week (between 1 and 7, inclusive)
WeekdayName Returns the weekday name of a specified day of the week
Year Returns a number that represents the year
EXAMPLES
17
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<html>
<body>
<script type="text/vbscript">
document.write("Today's date is " & date())
document.write("<br />")
document.write("The time is " & time())
</script>
</body>
</html>
<html>
<body>
<script type="text/vbscript">
document.write("Today's day is " &
WeekdayName(weekday(date)))
document.write("<br />")
document.write("The month is " &
MonthName(month(date)))
</script>
</body>
</html>
18
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<html>
<body>
<script type="text/vbscript">
document.write(FormatDateTime(date(),
vbgeneraldate))
document.write("<br />")
document.write(FormatDateTime(date(),
vblongdate))
document.write("<br />")
document.write(FormatDateTime(date(),
vbshortdate))
document.write("<br />")
document.write(FormatDateTime(now(),
vblongtime))
document.write("<br />")
document.write(FormatDateTime(now(),
vbshorttime))
</script>
<p>Syntax for FormatDateTime:
FormatDateTime(date,namedformat).</p>
</body>
</html>
Conversion Functions
Function Description
Asc Converts the first letter in a string to ANSI code
CBool Converts an expression to a variant of subtype Boolean
CByte Converts an expression to a variant of subtype Byte
CCur Converts an expression to a variant of subtype Currency
CDate Converts a valid date and time expression to the variant of subtype Date
CDbl Converts an expression to a variant of subtype Double
Chr Converts the specified ANSI code to a character
CInt Converts an expression to a variant of subtype Integer
CLng Converts an expression to a variant of subtype Long
CSng Converts an expression to a variant of subtype Single
CStr Converts an expression to a variant of subtype String
Hex Returns the hexadecimal value of a specified number
Oct Returns the octal value of a specified number
Format Functions
19
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
Function Description
FormatCurrency Returns an expression formatted as a currency value
FormatDateTime Returns an expression formatted as a date or time
FormatNumber Returns an expression formatted as a number
FormatPercent Returns an expression formatted as a percentage
Math Functions
Function Description
Abs Returns the absolute value of a specified number
Atn Returns the arctangent of a specified number
Cos Returns the cosine of a specified number (angle)
Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number
Int Returns the integer part of a specified number
Fix Returns the integer part of a specified number
Log Returns the natural logarithm of a specified number
Oct Returns the octal value of a specified number
Rnd Returns a random number less than 1 but greater or equal to 0
Sgn Returns an integer that indicates the sign of a specified number
Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified number
Tan Returns the tangent of a specified number (angle)
Round a number
<html>
<body>
<script type="text/vbscript">
i = 48.66776677
j = 48.3333333
document.write(Round(i))
document.write("<br />")
document.write(Round(j))
</script>
</body>
</html>
20
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<html>
<body>
<script type="text/vbscript">
randomize()
document.write(Rnd())
</script>
</body>
</html>
ARRAY FUNCTIONS
Function Description
Array Returns a variant containing an array
Filter Returns a zero-based array that contains a subset of a string array based on a
filter criteria
IsArray Returns a Boolean value that indicates whether a specified variable is an array
Join Returns a string that consists of a number of substrings in an array
LBound Returns the smallest subscript for the indicated dimension of an array
Split Returns a zero-based, one-dimensional array that contains a specified number
of substrings
UBound Returns the largest subscript for the indicated dimension of an array
STRING FUNCTIONS
Function Description
InStr Returns the position of the first occurrence of one string within another. The
search begins at the first character of the string
InStrRev Returns the position of the first occurrence of one string within another. The
search begins at the last character of the string
LCase Converts a specified string to lowercase
Left Returns a specified number of characters from the left side of a string
Len Returns the number of characters in a string
LTrim Removes spaces on the left side of a string
RTrim Removes spaces on the right side of a string
21
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
Trim Removes spaces on both the left and the right side of a string
Mid Returns a specified number of characters from a string
Replace Replaces a specified part of a string with another string a specified number of
times
Right Returns a specified number of characters from the right side of a string
Space Returns a string that consists of a specified number of spaces
StrComp Compares two strings and returns a value that represents the result of the
comparison
String Returns a string that contains a repeating character of a specified length
StrReverse Reverses a string
UCase Converts a specified string to uppercase
<html>
<body>
<script type="text/vbscript">
txt="Have a nice day!"
document.write(ucase(txt))
document.write("<br />")
document.write(lcase(txt))
</script>
</body>
</html>
REVERSE A STRING
<html>
<body>
<script type="text/vbscript">
sometext = "Hello Everyone!"
document.write(strReverse(sometext))
</script>
</body>
</html>
22
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
<html>
<body>
<script type="text/vbscript">
sometext="Welcome to this Web!!"
document.write(Replace(sometext, "Web",
"Page"))
</script>
</body>
</html>
Other Functions
Function Description
CreateObject Creates an object of a specified type
Eval Evaluates an expression and returns the result
GetLocale Returns the current locale ID
GetObject Returns a reference to an automation object from a file
GetRef Allows you to connect a VBScript procedure to a DHTML event on your pages
InputBox Displays a dialog box, where the user can write some input and/or click on a
button, and returns the contents
IsEmpty Returns a Boolean value that indicates whether a specified variable has been
initialized or not
IsNull Returns a Boolean value that indicates whether a specified expression contains
no valid data (Null)
IsNumeric Returns a Boolean value that indicates whether a specified expression can be
evaluated as a number
IsObject Returns a Boolean value that indicates whether the specified expression is an
automation object
23
VBSCRIPT COMPLETE REFERENCE
SAMPAT PATNAIK
MPX TECHNOLOGIES
24