Sunteți pe pagina 1din 38

Envision , Evolve, Unleash

VBScript

By Srinivas & Ashok


Overview

• VBScript is a Scripting Language.


• VBScript is a Subset of VB.
• VBScript is Interpreted at Runtime.

10/22/08 2
Pros. and Cons. of Runtime Compilation
Advantages of Runtime Compilation:
Can be embedded with other types of code.

Disadvantages of Runtime Compilation :

Compilation will be slower.

Transparent code.

Syntax errors aren’t caught until runtime.

10/22/08 3
Advantages of Using VBScript

• Good Platform coverage.


• VBScript source implementation from
Microsoft is completely free of charge.

10/22/08 4
What Can You Do with VBScript

• Can do client side validations


• Reduces load on web server by
performing some validations at client side
• Can fetch data from Database.

10/22/08 5
Data Types

Variables can hold a wide range of data:


numbers,dates,text, and other more
specialized categories.The different
“categories “ into which values can be
divided- numbers, dates, text and so on –
are called data types.

10/22/08 6
Why Data Types are Important

A programmer must declare a variable for a specific


purpose, give the variable a specific name, and declare
the intention to store only a specific type of data in that
variable.If all the elements are neatly segmented and
maintained in consistent manner.Program is likely to do
without a lot of bugs.

VBScript does not have any syntax for declaring a


variable using specific data type.

All the VBScript variables have the same data type,


Variant
10/22/08 7
The Variant:VBScript’s Only Data Type

• Testing for and Coercing Subtypes


• Implicit Type Coercion
• Empty and Null
• The Object Subtype
• The Error Subtype

10/22/08 8
Arrays as Complex Data Types

• What is an Array?
• Arrays Have Dimensions
• Array Bounds and Declaring Arrays
• Accessing Arrays with Subscripts
• Looping through Arrays
• Erasing Arrays
• Using VarType() with Arrays

10/22/08 9
What is a Variable?

A variable is a "container" for information you want to


store. A variable's value can change during the script.
You can refer to a variable by name to see its value or
to change its value. In VBScript, all variables are of
type variant, that can store different types of data.

Declare variables explicitly in your script using the Dim


statement.
Eg. Dim Degrees Fahrenheit

You can also declare a variable implicitly by simply using


its name in your script.

10/22/08 10
Option Explicit

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.

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

10/22/08 11
Procedures and Functions

• Procedures and Functions allow you to modularize the


code in your script into the named blocks of code that
perform specific function.

• Function is a named block of code that returns a value to


the calling code, while a procedure is a named block of
code that does not return a value to the calling code.

10/22/08 12
Procedures and Functions

• A named block of code.


• Calling Code
• Returning a value

Procedure Syntax
[Public| Private] Sub Name([Arg1], [Arg2])
[code inside the procedure]
End Sub

10/22/08 13
Procedures and Functions

• Public is by default
• Rules for naming a procedure is same as that of declaring
a variable.

Function Syntax
[Public | Private] Function Name ([Arg1], [Arg2])
[Code of the function ]
End Function

10/22/08 14
Calling Procedures and Functions

Procedure Calling :

Legal
Greet User “Bill”
Call Greet User (“Bill”)
Not legal
Greet User (“Bill”)
Call Greet User “Bill”

10/22/08 15
Calling Procedures and Functions

Function Calling :

Returning a value
Legal
LngSum = AddNumbers(10,20)
Illegal
LngSum = AddNumbers 10,20
Not Returning a value

10/22/08 16
Calling Procedures and Functions

Legal
Call AddNumbers(10,20)
Illegal
LngSum = Call AddNumbers(10,20)
Legal
AddNumbers 10,20

10/22/08 17
Optional Arguments

• Procedures and Functions can have optional arguments.


If an argument is optional, then you don’t have to pass
anything to it.

• Built- in VBScript procedures you call (Such as MsgBox)


can have optional arguments, but your own VBScript
procedures cannot.

10/22/08 18
Exiting a Procedure or Function

• A Procedure or Function will exit naturally when the last


line of code inside of it done executing, However,
sometimes you want to terminate a procedure sooner
than that. In this case, you can use either of the
statements Exit Sub (for procedure) or Exit Function (for
Functions).

• The code will stop executing whenever the Exit


statement appears and the flow of the code will return to
the caller.

10/22/08 19
Inbuilt features

Inbuilt Functions: The functions described below are only


few of among an exhaustive list. For the full list of
functions refer to VBScript Language Reference.

Array Function
Returns a Variant containing an array.
Eg. A = Array(10,20,30) ‘returns an array

InputBox Function: Displays a prompt in a dialog box,


waits for the user to input text or click a button, and
returns the contents of the text box.
Eg. Input = InputBox("Enter your name")

10/22/08 20
Built in Functions

1.Date/Time functions eg:Date,DateAdd,DateDiff,IsDate


2.Conversion functions eg:CBool,CByte,CInt,CStrt
3.Format functions eg:FormatCurrency,FormatNumber
4.Math functions eg:Int,Log,Sin
5.Array functions eg:Array,IsArray,Spilt,LBound
6.String function
eg:LTrim,Rtrim,Replace,StrComp,InStr,Mid
7.Other function
eg:CreateObject,GetObject,Msgbox,Inputbox,IsEmpty,Is
Null,IsNumeric

10/22/08 21
Built in Functions

Join Function
Returns a string created by joining a number of substrings contained in an
array.
Join(list[, delimiter])
The default delimiter is space.
Eg. Join(myArray, “,”) ‘Returns a concantenated string of all the elements in
the array delimited by a comma .

Left Function
Returns a specified number of characters from the left side of a string.
Left(string, length)
Eg. MyString = Left(“abcd”, 3) returns abc

Right Function
Returns a specified number of characters from the right side of a string.
Right(string, length)
Eg. MyString = Left(“abcd”, 3) returns abc

10/22/08 22
Built in Functions

Replace Function:Returns a string in which a specified substring has


been replaced with another substring a specified number of times.

Eg. MyString = Replace("XXpXXPXXp", "p", "Y") ' A binary


comparison starting at the beginning ‘of the string. Returns
"XXYXXPXXY".

String Function:Returns a repeating character string of the length


specified.
Eg. MyString = String(5, "*") ' Returns "*****".

UCase Function:Returns a string that has been converted to


uppercase.
Eg. MyWord = UCase("Hello World") ' Returns "HELLO WORLD".

10/22/08 23
Built in Functions Examples

1.InStr--Returns the position of the first occurrence of one string within another. The search begins at
the first character of the string.
Eg: Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP" ' String to search in.
SearchChar = "P" ' Search for "P".
MyPos = Instr(4, SearchString, SearchChar, 1) ' A textual comparison starting at position 4.
Returns 6.
2.Mid-Returns a specified number of characters from a string
Dim MyString
MyString = "The dog jumps" ' Initialize string.
Mid(MyString, 5, 3) = "fox" ' MyString = "The fox jumps".
Mid(MyString, 5) = "cow" ' MyString = "The cow jumps".

3.StrComp-Compares two strings and returns a value that represents the result of the comparison
Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd" ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1) ' Returns 0.if both equal
MyComp = StrComp(MyStr1, MyStr2, 0) ' Returns -1. MyStr2> MyStr1
MyComp = StrComp(MyStr2, MyStr1) ' Returns 1. MyStr1> MyStr2
4.Len-Returns the number of characters in a string

10/22/08 24
5. LTrim-Removes spaces on the left side of a string

6.RTrim-Removes spaces on the right side of a string

VBScript Keywords

Empty : The Empty keyword is used to indicate an


uninitialized variable value.
False: Boolean false.
True: Boolean true.
Nothing : The Nothing keyword in VBScript is used to
disassociate an object variable from any actual
object.
Eg. Set MyObject = Nothing
Null: The Null keyword is used to indicate that a
variable contains no valid data.
10/22/08 25
Variable Declarations and Scope

Scope and Lifetime of Variables


A variable's scope is determined by where it is declared. Variable
declared within a procedure, can be accessed only within that
procedure. It has local scope and is a procedure-level variable.
Variables declared outside a procedure, are visible to all the
procedures in your script. This is a script-level variable, and it has
script-level scope.

A variable’s scope is a boundary within which a variable is valid and


accessible. The boundary within which a variable is declared is
directly related to the lifetime of that variable. Script code that is
executing outside of a variable’s scope cannot access that
variable. There are three types of scope that a VBScript variable
can have: Script- level scope, Procedure-level scope and Class-
level scope.

10/22/08 26
Variable Declarations and Scope

• There are three statements that you can use to declare


variables: Dim, Private and Public.
Dim: Used at Script or Procedure levels.
(Any variable declared at script level is available to the
entire script)
Private: Used at Script or Class level but not inside the
procedures or functions.
Public: Used at Class or script level. More meaning for
public is declaring at Class level.

10/22/08 27
Design Strategies for Scripts and Procedures

Here are some general principles to aid you in your script designs:
• Simple script files that perform one specific job with a limited
amount of code can be written as a single block of code without
any procedures or functions.

• As script files become more complex, look for ways to break the
logic down into subparts using, procedures, functions, and / or
classes.

• As you break the logic into subparts, keep the coordinating code
at the top of the script file.

• Design each procedure and function so that it has very specific


job and so that it does only the job. Give the procedure a good
descriptive name that indicates what job it does.

• If the value of a script – level variable needs to be changed,


use the coordinating code at the top of the script file to make the
change.
10/22/08 28
Passing Arguments to Functions and Procedures

ByRef and ByVal

Passing arguments by reference versus passing


arguments by value. As argument is defined either by
reference or by value depending on how it is declared
in the procedure or function definition.

A by reference argument is indicated with the ByRef


Keyword, whereas a by value argument can either be
indicated with the ByVal keyword or not specifying
either ByRef or ByVal – that is , if you do not specify
one or the other explicitly, ByVal is the default.

10/22/08 29
Literals and Named Constants

What is a Literal?
A literal is any piece of static data that appears in your
code that is not stored in a variable or named
constant. Literals can be strings of text, numbers,
dates, or Boolean values. For examples, the word
“Hello” in the Following code is a literal.
Literals:
• String literal is enclosed in quotation marks (" ").Eg A
= “123”
• Date literals and time literals are represented by
enclosing them in number signs (#) Eg. Const
CutoffDate = #6-1-97#
Example: Dim strMessage
strMessage = “Hello”
MsgBox strMessage
10/22/08 30
Literals and Named Constants

• What is a Named Constant?


A named constant is similar to a variable, except that its
value cannot be changed at runtime. A variable is
dynamic.
A named constant is static, once defined , it cannot be
changed by any code during runtime- hence the
name “constant”.
Constants:
User Defined constants are created using Const
statement.
Eg. Const MyString = "This is my string."

10/22/08 31
Using Named constants in place of Literals

• Named constants can decrease bugs


• Named constants can increase clarity
• Replacing the large text literal will allow user to easily
type the code.

Named Constants Rules:


Rule#1:If you are using a literal only once, it’s probably
okay to use it instead of creating a named constant.
Rule#2: If using the constant in place of a literal makes the
meaning of the code more clear, use the constant

10/22/08 32
Built-In VBScript Constants

Many VBScript hosts, such as windows Script Host and


Active Server Pages, support the use of constants that
are built into VBscript.

Useful for two reasons: First, it is hard to remember all


VBScript functions and procedures use as parameters
and return values. Second , using named constants
makes code a lot easier to read.

10/22/08 33
Conditional Statements

If...Then...Else
To run only one statement for a True condition, use the single-line syntax.
Eg. If myDate < Now Then myDate = Now
To run more than one line of code, you must use the multiple-line (or block)
syntax. This syntax includes the End If statement
Eg. If value = 0 Then
AlertLabel.Font.Italic = True
End If
Deciding Between Several Alternatives
Using ElseIf and Else clauses, you can control program flow based on
different possibilities.
Eg. If value = 0 Then
MsgBox value
ElseIf value = 1 Then
MsgBox value
Else
Msgbox "Value out of range!“
End If 10/22/08 34
Select Case

A Select Case structure works with a single test expression that is evaluated
once, at the top of the structure. The result of the expression is then compared
with the values for each Case in the structure. If there is a match, the block of
statements associated with that Case is executed.

Select Case payment


Case "Cash"
MsgBox "You are going to pay cash"
Case "Visa"
MsgBox "You are going to pay with visa"
Case "Master"
MsgBox "You are going to pay with Master"
Case Else
MsgBox "Unknown method of payment"
End Select

Case Else is similar to default and is optional.


10/22/08 35
Looping Through Code

Do Loops
The statements are repeated either while a condition is True or until a
condition becomes True.
Eg. Do While myNum > 10
myNum = myNum – 1
counter = counter + 1
Loop
Eg. Do Until myNum = 10
myNum = myNum – 1
counter = counter + 1
Loop
While...Wend
Eg. while myNum <> 10
myNum = myNum – 1
counter = counter + 1
wend
*Because of the lack of flexibility in While...Wend, it is recommended that
you use Do...Loop instead.
10/22/08 36
For...Next

For loops, use a counter variable whose value increases or decreases with each repetition of the
loop. You can use a For...Next statement to run a block of code, when you know how many
repetitions you want. You can use a counter variable that increases or decreases with each
repetition of the loop, like this:
For i=1 to 10
some code
Next
Using the Step keyword, you can increase or decrease the counter variable by the value you
specify.
Eg . For j = 2 To 10 Step 2
total = total + j
Next
Step can be any integer. Default step is 1.
For Each…Next
This statement is used to iterate over a collection.
Dim names(2)
names(0) = "Tove"
names(1) = "Jani"
names(2) = "Hege"
For Each x In names
MsgBox x
Next
End Sub
Result:Displays “Tove” first time,next “Jani”,next time “Hege”
10/22/08 37
Exit Statement

You can exit a Do or a For loop by using the Exit


statement.

Eg. Do until i < 100


If i = a Then Exit Do
Loop
Eg. For I = 1 to 100
If i = a Then Exit For
Next

10/22/08 38

S-ar putea să vă placă și