0% found this document useful (0 votes)
15 views

Basic of VB Script

Basic of Vb Script
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Basic of VB Script

Basic of Vb Script
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 59

BASIC OF VB SCRIPT

S.Kavitha
Head & Assistant Professor
Department of Computer Science
Sri Sarada Niketan College of Science for Women,Karur.
CONTENTS OF VB SCRIPT
• INTRODUCTION
• DATA TYPE
• VARIABLE
• OPERATORS
• CONTROL STRUCTURE
• BUILT IN FUNCTION
• ADVANTAGES OF VB SCRIPT
• DISADVANTAGES OF VB SCRIPT
INTRODUCTION

• Visual Basic Script recently introduced by Microsoft


represents a step further towards active web pages. It is a
subset of the Visual Basic programming language that is fully
compatible with Visual Basic and Visual Basic for Applications.
• VBScript was created to allow web page developers the ability
to create dynamic web pages for their viewers who used
Internet Explorer. With HTML, not a lot can be done to make
a web page interactive, but VBScript unlocked many tools
like: the ability to print the current date and time, access to
the web servers file system, and allow advanced web
programmers to develop web applications.
• To use Visual Basic Script within a HTML document, the code
needs to be wrapped in <SCRIPT> ... </SCRIPT>
vbscript script creation

• This first script will be very basic and will write


"Hello World" to the browser window, just as
if you had typed it in HTML. This may not
seem very important, but it will give you a
chance to see the VBScript Syntax without
getting to complex.
VBScript Code:

• <html>
• <body>
• <script type="text/vbscript">
document.write("Hello World")
• </script>
• </body>
• </html>
• VBScript only runs on Internet Explorer browsers.
• Output: Hello World
vbscript <script> tag

• In the above example you saw the basic cookie


cutter for inserting a script into a web page. The
HTML script tag lets the browser know we are
going to use a script and the
attribute type specifies which scripting language
we are using. VBScript's type is "text/vbscript".
• All the VBScript code that you write must be
contained within script tags, otherwise they will
not function properly.
vbscript syntax

• If you are an expert Visual Basic programmer


then you will be pleasantly surprised to know
that VBScript has nearly identical syntax to
Visual Basic. However, if you are a
programmer or only know the basics of HTML
then VBScript code may look a little strange to
you. This lesson will point out the most
important things about VBScript syntax so you
can avoid common potholes.
vbscript: no semicolons!
• If you have programmed before, you will be
quite accustomed to placing a semicolon at
the end of every statement. In VB this is
unnecessary because a newline symbolizes
the end of the statement. This example will
print out 3 separate phrases to the
browser. Note: There are 0 semicolons!
VBScript Code:

<script type="text/vbscript">
document.write("No semicolons")
document.write(" were injured in the making")
document.write(" of this tutorial!")
</script>
• Output:
• No semicolons were injured in the making of
this tutorial!
vbscript multiple line syntax

• The syntax is that placing a newline in your


VBScript signifies the end of a statement, much
like a semicolon would. However, what happens
if your code is so long that absolutely must place
your code on multiple lines?
• Well, Microsoft has included a special character
for these multiple lines of code: the underscore
"_". The following example contains an
exceptionally longwrite statement that we will
break up string concatenation and the multiple
line special character.
VBScript Code:

<script type="text/vbscript">
document.write("This is a very long write " &_
"statement that will need to be placed onto
three " &_ "lines to be readable!")
</script>
• Output:
• This is a very long write statement that will
need to be placed onto three lines to be
readable!
vbscript syntax review

• VBScript is a client-side scripting language that


is based off of Microsoft's Visual Basic
programming language. No semicolons are
used at the end of statements, only newlines
are used to end a statement.
• If you want to access methods of an object
then use a period "." and an underscore is
used for statements that go multiple lines!
Data type of vbscript

• VBScript has only one data type called a Variant. A Variant is a


special kind of data type that can contain different kinds of
information, depending on how it's used. Because Variant is the
only data type in VBScript, it's also the data type returned by all
functions in VBScript.At its simplest, a Variant can contain either
numeric or string information.
• A Variant behaves as a number when you use it in a numeric
context and as a string when you use it in a string context. That is, if
you're working with data that looks like numbers, VBScript assumes
that it is numbers and does the thing that is most appropriate for
numbers. Similarly, if you're working with data that can only be
string data, VBScript treats it as string data. Of course, you can
always make numbers behave as strings by enclosing them in
quotation marks (" ").
Variant Subtypes

• Beyond the simple numeric or string classifications,


a Variant can make further distinctions about the specific
nature of numeric information. For example, you can have
numeric information that represents a date or a time.
When used with other date or time data, the result is
always expressed as a date or a time. Of course, you can
also have a rich variety of numeric information ranging in
size from Boolean values to huge floating-point numbers.
These different categories of information that can be
contained in a Variant are called subtypes. Most of the
time, you can just put the kind of data you want in
a Variant, and the Variant behaves in a way that is most
appropriate for the data it contains
The following table shows the subtypes of data that
a Variant can contain.
Subtype Description
Empty Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.

Null Variant intentionally contains no valid data.

Boolean Contains either True or False.

Byte Contains integer in the range 0 to 255.

Integer Contains integer in the range -32,768 to 32,767.

Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

Long Contains integer in the range -2,147,483,648 to 2,147,483,647.

Single Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values;
1.401298E-45 to 3.402823E38 for positive values.
Double Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324
for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Date (Time) Contains a number that represents a date between January 1, 100 to December 31, 9999.

String Contains a variable-length string that can be up to approximately 2 billion characters in length.

Object Contains an object.

Error Contains an error number.


VARIABLE of vbscript

• A variable is a named location in computer


memory that you can use for storage of data
during the execution of your scripts. You can
use variables to:
• Store input from the user gathered via your
web page
• Save data returned from functions
• Hold results from calculations
Declaring Variables

• Creating variables in VBScript is most often referred to as "declaring"


variables.
• You can declare VBScript variables with the Dim, Public or the Private
statement. Like this:
• Dim x
• You declare multiple variables by separating each variable name with a
comma. For example:
• Dim Top, Bottom, Left, Right

You can also declare a variable implicitly by simply using its name in your
script. That is not generally a good practice because you could misspell
the variable name in one or more places, causing unexpected results
when your script is run. For that reason, the Option Explicit statement is
available to require explicit declaration of all variables. The Option
Explicit statement should be the first statement in your script.
Option Explicit

• As mentioned, it's good practice to declare all variables


before using them. Occasionally, if you're in a hurry, you
might forget to do this. Then, one day, you might misspell
the variable name and all sorts of problems could start
occurring with your script.
• VBScript has a way of ensuring you declare all your
variables. This is done with the Option Explicit statement:
• <script type="text/vbscript">
• Option Explicit
• Dim firstName
• Dim age
• </script>
Naming Restrictions

• Variable names follow the standard rules for


naming anything in VBScript. A variable name:
• Must begin with an alphabetic character.
• Cannot contain an embedded period.
• Must not exceed 255 characters.
• Must be unique in the scope in which it is
declared.
Assigning Values to Variables

• Values are assigned to variables creating an


expression as follows: the variable is on the left
side of the expression and the value you want to
assign to the variable is on the right. For
example:
• B = 200
• You represent date literals and time literals by
enclosing them in number signs (#), as shown in
the following example.
• CutoffDate = #06/18/2008#
• CutoffTime = #3:36:00 PM#
Example of Assign Values to your Variables

• <script type="text/vbscript">
• Option Explicit
• Dim firstName
• Dim age
• firstName = "Borat“
• age = 25
• </script>
Display your Variables

• <script type="text/vbscript">
• Option Explicit
• Dim firstName
• Dim age
• firstName = "Borat"
• age = 25
• document.write("Firstname: " & firstName & "</br />")
• document.write("Age: " & age)
• </script>
• Output:
Firstname: Borat
Age: 25
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.
VBScript Array Variables

• 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)="Tove"
names(1)="Jani"
names(2)="Stale“
• Similarly, the data can be retrieved from any element using the index of
the particular array element you want. Like this:
• mother=names(0)
• You can have up to 60 dimensions in an array. Multiple dimensions are
declared by separating the numbers in the parentheses with commas. Here
we have a two-dimensional array consisting of 5 rows and 7 columns:
• Dim table(4,6)
Asign data to a two-dimensional array:
• <html>
<body>
<script type="text/vbscript">
Dim x(2,2)
x(0,0)="Volvo"
x(0,1)="BMW"
x(0,2)="Ford"
x(1,0)="Apple"
x(1,1)="Orange"
x(1,2)="Banana"
x(2,0)="Coke"
x(2,1)="Pepsi"
x(2,2)="Sprite"
for i=0 to 2
document.write("<p>")
for j=0 to 2
document.write(x(i,j) & "<br />")
next
document.write("</p>")
next
</script>
</body>
</html>
output
OPERATORS of vbscript

• Operators are used to "do operations" or


manipulate variables and values. For example,
addition is an example of a mathematical
operator and concatenation is an example of a
string operator. The plus sign "+" is
the operator used in programming language
to represent this mathematical addition
operation.
VBScript's many operators can be separated into
four semi-distinct categories:
• Math Operators
• Comparison Operators
• Logic Operators
• String Concatenation Operator
Math Operators

• When you want to perform addition,


subtraction, multiplication, and other
mathematical operations on numbers and
variables use the operators listed below.
Operator English Example Result
+ Add 8+7 15
- Subtract 11-10 1
* Multiply 7*8 56
/ Divide 8/2 4
^ Exponent 2^4 16
Mod Modulus 15 Mod 10 5
vbscript operators: comparison

• When you want to compare two numbers to see which is


bigger, if they're equal, or some other type of relationship use
the comparison operators listed below. Common uses of
comparison operators are within conditional statements like
an If Statement or the condition check in a While Loop.
Operator English Example Result
= Equal To 10 =1 4 False
> Greater Than 10 > 14 False
< Less Than 10 < 14 True
Greater Than Or Equal
>= 10 >= 14 False
To
<= Less Than Or Equal To 10 <= 14 True
<> Not Equal To 10 <> 14 5
vbscript operators: logic

• Logic operators are used to manipulate and create logical


statements. For example if you wanted a
variable shoeSize to be equal to 10 or 11 then you would do
something like:
• VBScript Code:
• <script type="text/vbscript">
• Dim shoeSize
• shoeSize = 10
• If shoeSize = 10 Or shoeSize = 12 Then
• 'Some code
• EndIf
• </script>
vbscript operators: logic
• A detailed explanation of Logic and Logic Operators are
beyond the scope of this tutorial, but we do have a list of the
various logic operators available to you in VBScript.

Operator English Example Result


Not Inverts Truth Value Not False True
Or Either Can Be True True Or False True
And Both Must Be True True And False False
vbscript string concatenation operator

• When you have various strings that you would like to


combine into one string use the concatenation
operator. The concatenation operator acts as a glue
between the two or more strings you wish to attach,
effectively making them into one string. String
concatenation is often used when using
the document.writefunction.

Operator English Example Result


"Hello" & "
& Connected To "Hello there
there"
Conditional statements

• Conditional Statements:Conditional statements are


used to perform different actions for different
decisions. In VBScript we have four conditional
statements:
• If statement - executes a set of code when a condition
is true
• If...Then...Else statement - select one of two sets of
lines to execute
• If...Then...ElseIf statement - select one of many sets of
lines to execute
• Select Case statement - select one of many sets of
lines to execute
If Statement

• if Age = 100 Then


MsgBox "Congratulations!“
An If statement first
checks to see if the specified condition
evaluates toTrue or False. If it evaluates
to True, then it evaluates a set of statements.
In the example above, the "Congratulations!"
message box is only displayed ifAge = 100, i.e.
if Age is equal to 100.
If...Then...Else statement
• If the condition in an if statement is true, then
the code following the condition will be
executed. But what if you wanted something to
happen if it is false? What if you wanted one
thing to happen if the condition is true, and
something else to happen if the condition is
false? This is where the else statement comes in.
The else statement works together with the if
statement and executes certain code if the
condition in the if statement is false.
Example
If Age = 100 Then
MsgBox "Congratulations!“
Else
MsgBox "You're still a young chicken!"
End If
Now we introduce the Else construct.
If the condition evaluates to True, the first set of
statements are executed. Otherwise, the set of
statements after the Else statement are
executed.
If...Then...ElseIf statement
• The if statement tests a single condition and performs an
action if that condition is true and the else statement
performs an action if the condition in the if statement is
false, but what if there are more than two possibilities?
Surely, any condition can be only true or false, but what if
you needed to test a variable for more than one value? This
is where the elseif statement comes in. The elseif
statement is used in conjunction with the if statement.
Unlike the else statement, it does not specifically perform a
certain action if the condition in the if statement is false,
but rather it performs an action if the condition in the if
statement is another specific value specified in the elseif
statement itself.

Example
• <script type="text/vbscript">
• Dim X
• X=7
• if X = 5 then
• document.write("X is equal to 5")
• elseif X = 7
• then document.write("X is equal to 7")
• end if
• </script>
• Output:
• X is equal to 7
Select Case statement
• The Select statement is specifically designed for comparing one
variable to a number of possible values. It can be thought of as a
substitute for the if, elseif, else structure.
• elect Case is useful when there are many conditions to be checked.
• Syntax
• Select Case expression
• Case value1 Case value2 ...
• Case Else
• End Select
With Select Case, expression is checked for
equality against each ofvalue1, value2, ... until a match is found. If
no values match, then the Case Else statement is executed.
Example
• <script type="text/vbscript">
• Dim X X = 7
• select case X
• case 1 document.write("X is equal to 1")
• case 2 document.write("X is equal to 2")
• case 3 document.write("X is equal to 3")
• case 7 document.write("X is equal to 7")
• case else document.write("X is not equal to any of the
values specified")
• end select
• </script>
• Output: X is equal to 7
Looping or controlling 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 statement - runs code a specified
number of times
• For Each...Next statement - runs code for each
item in a collection or each element of an array
• The do while loop - loops while or until a
condition is true
• While...Wend statement - Do not use it - use the
Do...Loop statement instead
For...Next statement
• 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 Nextstatement 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>
output
• The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
For Each...Next Loop

• A For Each...Next loop repeats a block of code for each item in a collection, or for each element of
an array.example:
• <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>
• Output:
• Volvo
Saab
BMW
The do while loop
• The Do … Loop statement is very useful (like, for …
next and Select … case) to execute a block of code
more than once. However, where it differs from the
other two is that the Do … Loop statement executes
the code as long as (while) a condition is true or until a
condition becomes true.
• Typical uses of a Do … Loop are in cases where you
may not know how many times you need to execute
the code section because it could vary from situation
to situation, like when reading in a file or taking in
keyboard input.
Example:
• <script type="text/javascript">
Dim num num = 0
• do while num < 30
• num = num + 5
• document.write(num & "<br />")
• loop
• </script>
• Output:
• 5
• 10
• 15
• 20
• 25
• 30

In the above example, a variable named num is given the value 0. The condition in the while loop is
that while num is less than 30, 5 should be added to num. Once the value of num is greater than
30, the loop will stop executing. The loop prints the current value of numfollowed by a line break
through each iteration.
BUILT IN FUNCTION

• There are many type of built in function in vbscript.


• Date/Time Functions
• Conversion Functions
• Format Functions
• Math Functions
• Array Functions
• String Functions
• Other 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 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)
Date/Time Functions
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
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

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)


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

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


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

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

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)

RGB Returns a number that represents an RGB color value

Round Rounds a number


ADVANTAGES OF VB SCRIPT
• You always have up-to-date pages with a correctly
hyperlinked menu.
• The menu does not use Javascript and frames.
• You pages can be easily copied or transferred into any
other folder or computer - and links do not become broken,
because they are relative.
• Since each menu element has its own CSS class, it can have
any look you wish.
• You receive pages which are already HTML- and CSS-
validated. Only your own content must be validated
additionally.
• Since the program script is simple enough, you can add
features and optimize it.
DISADVANTAGES OF VB SCRIPT
• Some of the syntax is very different from C++ and will
probably frustrate experienced programmers.
– “=” is used for both assignment and comparison
– the “()” characters are used less often then in C++
– "NOT" does both boolean and bitwise NOT (so NOT true is false,
but NOT -1 is -2!)
• VBScript is not as widely used in web technology as
JScript/Javascript, because it is only supported on
Windows. XSI is able to support VBScript on the Linux
platform, but few developers from a purely linux/unix
background are familiar with VBScript.
• As a basic (sic) language the error handling is primitive (“on
error resume next”, “option explicit”)

You might also like