tag is used to embed VBScript code, which can execute when pages load or in response to events. Variables are used to store and represent values, and can be declared with statements like Dim. VBScript supports procedures like Subs and Functions to organize code into reusable blocks. Conditional statements allow scripts to make decisions and run different code based on conditions."> tag is used to embed VBScript code, which can execute when pages load or in response to events. Variables are used to store and represent values, and can be declared with statements like Dim. VBScript supports procedures like Subs and Functions to organize code into reusable blocks. Conditional statements allow scripts to make decisions and run different code based on conditions.">
VB Script: Vbscript Introduction
VB Script: Vbscript Introduction
• VBScript Introduction
• VBScript How To
The HTML <script> tag is used to insert a VBScript into an HTML page.
Put a VBScript into an HTML Page
The example below shows how to use VBSript to write text on a web page:
<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
The example below shows how to add HTML tags to the VBScript:
<html>
<body>
<script type="text/vbscript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>
1. Example Explained
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 document.write command is a standard VBScript command for writing output to a page.
By entering the document.write command between the <script> and </script> tags, the browser will
recognize it as a VBScript command and execute the code line. In this case the browser will write
Hello World! to the page:
<html>
<body>
<script type="text/vbscript">
document.write("Hello World!")
</script>
</body>
</html>
2. 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>
• VBScript Variables
Variables are "containers" for storing information.
Do You Remember Algebra from School?
Do you remember algebra from school? x=5, y=6, z=x+y
Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use
the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions
(z=x+y).
1. VBScript Variables
As with algebra, VBScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for VBScript variable names:
i. Must begin with a letter
ii. Cannot contain a period (.)
iii. Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of data.
Now you have also created a variable. The name of the variable is "carname". 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 "carname" variable to "carnime", the script will automatically create a
new variable called "carnime". 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:
Dim carname
carname=some value
3. Lifetime of Variables
How long a variable exists is its lifetime.
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.
• VBScript Procedures
In VBScript, there are two kinds of procedures:
i. Sub procedure
ii. Function procedure
or
Sub mysub(argument1,argument2)
some statements
End Sub
or
Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function
1. Conditional Statements
Conditional statements are used to perform different actions for different decisions.
In VBScript we have four conditional statements:
i. If statement - executes a set of code when a condition is true
ii. If...Then...Else statement - select one of two sets of lines to execute
iii. If...Then...ElseIf statement - select one of many sets of lines to execute
iv. Select Case statement - select one of many sets of lines to execute
1. If...Then...Else
Use the If...Then...Else statement if you want to
i. execute some code if a condition is true
ii. select one of two blocks of code to execute
If you want to execute only one statement when a condition is true, you can write the code on one
line:
If i=10 Then msgbox "Hello"
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:
<body onload="greeting()">
</body>
</html>
Try it yourself »
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).
1. If...Then...ElseIf
You can use the If...Then...ElseIf statement if you want to select one of many blocks of code to
execute:
<body onload="greeting()">
</body>
</html>
Try it yourself »
2. Select Case
You can also use the "Select Case" statement if you want to select one of many blocks of code to
execute:
Example (IE Only)
<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>
</html>
Try it yourself »
This is how it works: 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.
• VBScript Looping
1.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:
i. For...Next statement - runs code a specified number of times
ii. For Each...Next statement - runs code for each item in a collection or each element of
an array
iii. Do...Loop statement - loops while or until a condition is true
iv. While...Wend statement - Do not use it - use the Do...Loop statement instead
1. 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.
Example
<html>
<body>
<script type="text/vbscript">
For i = 0 To 5
document.write("The number is " & i & "<br />")
Next
</script>
</body>
</html>
Try it yourself »
Example
<html>
<body>
<script type="text/vbscript">
Dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
</body>
</html>
Try it yourself »
3. 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.
Repeat Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.
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.
Repeat Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.
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
You can exit a Do...Loop statement with the Exit Do keyword.
Do Until i=10
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.
• Examples
1. Date time
<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>
2. Display days
<html>
<body>
<p>VBScripts' function <b>WeekdayName</b> is used to get a weekday:</p>
<script type="text/vbscript">
document.write("<p>")
document.write(WeekDayName(1))
document.write("<br />")
document.write(WeekDayName(2))
document.write("</p><p>")
3. Display Month
<p>VBScripts' function <b>MonthName</b> is used to get a month:</p>
<script type="text/vbscript">
document.write("<p>")
document.write(MonthName(1))
document.write("<br />")
document.write(MonthName(2))
document.write("</p><p>")
7. Is this a date?
<html>
<body>
<script type="text/vbscript">
somedate="10/30/99"
document.write(IsDate(somedate))
</script>
</body>
</html>
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 the 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 the 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
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
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
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)
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
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
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
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
LoadPicture Returns a picture object. Available only on 32-bit platforms
MsgBox Displays a message box, waits for the user to click a button, and returns
a value that indicates which button the user clicked
RGB Returns a number that represents an RGB color value
Round Rounds a number
ScriptEngine Returns the scripting language in use
ScriptEngineBuildVersion Returns the build version number of the scripting engine in use
ScriptEngineMajorVersion Returns the major version number of the scripting engine in use
ScriptEngineMinorVersion Returns the minor version number of the scripting engine in use
SetLocale Sets the locale ID and returns the previous locale ID
TypeName Returns the subtype of a specified variable
VarType Returns a value that indicates the subtype of a specified variable
VBScript Keywords
Keyword Description
Empty Used to indicate an uninitialized variable value. A variable value is
uninitialized when it is first created and no value is assigned to it, or
when a variable value is explicitly set to empty.
Example:
Dim x 'the variable x is uninitialized!
x="ff" 'the variable x is NOT uninitialized anymore
x=Empty 'the variable x is uninitialized!
Note: This is not the same as Null!!
IsEmpty Used to test if a variable is uninitialized.
Example: If (IsEmpty(x)) 'is x uninitialized?
Nothing Used to indicate an uninitialized object value, or to disassociate an
object variable from an object to release system resources.
Example: Set myObject=Nothing
Is Nothing Used to test if a value is an initialized object.
Example: If (myObject Is Nothing) 'is it unset?
Note: If you compare a value to Nothing, you will not get the right
result! Example: If (myObject = Nothing) 'always false!
Null Used to indicate that a variable contains no valid data.
One way to think of Null is that someone has explicitly set the value to
"invalid", unlike Empty where the value is "not set".
Note: This is not the same as Empty or Nothing!!
Example: x=Null 'x contains no valid data
IsNull Used to test if a value contains invalid data.
Example: if (IsNull(x)) 'is x invalid?
True Used to indicate a Boolean condition that is correct (True has a value of
-1)
False Used to indicate a Boolean condition that is not correct (False has a
value of 0)