Friday 22 March 2013

qtp ref 2



Error Handling in QTP

Error Handling:
Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.

Within every Script we have to think about possible exceptions and how to handle them. Especially in the uppermost layers of the script, it is important to handle all exceptions.

Error Handling in QuickTest Professional:
QTP and VBScript give the Test Engineer some tools to handle errors and Exceptions.

Error Preventing:

A good method for using error handling is to try to prevent them.

When an error occurred, Report it in detail. When working with GUI objects, use the Window.Exist property. Every If…Then..End If statement has the Else part, the same for
Select Case. Use Case Else.

Error Handling Methods in QTP and VB Script:

a)    Synchronization
b)    Exist Property
c)    Recover Scenarios

d)    On Error Statement

Without an On Error statement, any run-time error that occurs is fatal: an error message is displayed, and execution stops.

Whenever possible, you use structured exception handling in your code, rather than resorting to unstructured exception handling and the On Error statement.

Parts:

GoToline

    Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to the specified line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.

GoTo 0

    Disables enabled error handler in the current procedure and resets it to Nothing.

GoTo -1

    Disables enabled exception in the current procedure and resets it to Nothing.

Resume Next

    Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point. Use this form rather than On Error GoTo when accessing objects.

On Error Resume Next 

Example1:
Dim a
a = 1
b-2
MsgBox a + b ' displays result without showing error

Example2:

Function Sum(Num1, Num2)
If IsNumeric(Num1) = False Or IsNumeric(Num2) = False Then
On Error Resume Next
Err.Raise vbObjectError + 100, "Sum Function", _
"One or more parameters are invalid."
Exit Function
End If
Sum = Num1 +Num2

End Function
 
Call Sum("gcreddy","QTP") 'Comes out without showing error
Call Sum(100,200) ' returns sum of 100,200 as 300
e)    Error Object

The Err object is an intrinsic object with global scope — there is no need to create an instance of it in your code. 

The properties of the Err object are set by the generator of an error — Visual Basic, an Automation object, or the VBScript programmer.
 
The default property of the Err object is Number.

 Err.Number contains an integer and can be used by an Automation object to return an SCODE.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.
The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err.
 
Example:

On Error Resume Next
Err.Raise 6   ' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear      ' Clear the error.

Err Object Properties and Methods

Properties

Description Property
 
HelpContext Property
 
HelpFile Property
 
Number Property
 
Source Property

Methods

Clear Method

Raise Method

f)    Exit Statement

Open 30 to 40 Orders in Flight Reservation Window, if some records not available handle the situation

Option Explicit
Dim Order_Number
If Not Window("Flight Reservation").Exist(3) Then
SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\HP\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set "gcreddy"
Dialog("Login").WinEdit("Password:").SetSecure "4c2e1e65bf29943393b6940f116d35231ce5fb7e"
Dialog("Login").WinButton("OK").Click
End If

For Order_Number= 30 to 40 step 1
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set Order_Number
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click

If Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").Exist(3) Then
Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click
Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click
Reporter.ReportEvent micWarning,"Res", "Up to "& Order_Number-1 &" Order only available"
Exit For
End If
Next
 

VB Script Fundamentals And Features


VB Script has several purposes:

a) Client side scripting in the Web (HTML)(Browser) (IE)

b) Server side scripting in the Web (ASP) (Web Server)(IIS)

c) Network Administration (Server OS) (WSH-Windows Script Host)

d) System Administration (Client OS) (WSH-Windows Script Host)

e) Test Automation (QTP) (QTP)

Our QTP Point of view below are the learning objectives:
a) Adding Comments

b) Data types

c) Declarations (Variables (Scalar and Array),Constants))

d) VB Script Operators

    i) Arithmetic Operators (Including Concatination operators)
    ii) Comparison
    iii) Logical
   
e) Flow Control Statements (a. Conditional Statements)
        i) If...Then...Else...End If
        ii) Select Case...Case...Case Else...End Select


f) Flow Control Statements (b. Loop Statements)
        i) For...Next
        ii) While...Wend
        iii) Do While/Until...Loop
        iV) For Each...Next

g) VB Script Procedures(Functions)
        i) Built-in Functions(String, Array, Math,Date & Time, Conversion functions etc...)
        ii) User defined
            1) Sub Procedures
            2) Function Procedures

h) Coding Convensions

--------------------

i) File System Operations

j) Excel sheet Operations

k) database Operations

l) Other VB Script Objects
        i) Dictionary Object
        ii) Word
        iii) Internet Explorer Object
        iV) RegExp Object

m) Regular expressions

k) Error Handling

VB Script Fundamentals And Features


VB Script has several purposes:

a) Client side scripting in the Web (HTML)(Browser) (IE)

b) Server side scripting in the Web (ASP) (Web Server)(IIS)

c) Network Administration (Server OS) (WSH-Windows Script Host)

d) System Administration (Client OS) (WSH-Windows Script Host)

e) Test Automation (QTP) (QTP)

Our QTP Point of view below are the learning objectives:
a) Adding Comments

b) Data types

c) Declarations (Variables (Scalar and Array),Constants))

d) VB Script Operators

    i) Arithmetic Operators (Including Concatination operators)
    ii) Comparison
    iii) Logical
   
e) Flow Control Statements (a. Conditional Statements)
        i) If...Then...Else...End If
        ii) Select Case...Case...Case Else...End Select


f) Flow Control Statements (b. Loop Statements)
        i) For...Next
        ii) While...Wend
        iii) Do While/Until...Loop
        iV) For Each...Next

g) VB Script Procedures(Functions)
        i) Built-in Functions(String, Array, Math,Date & Time, Conversion functions etc...)
        ii) User defined
            1) Sub Procedures
            2) Function Procedures

h) Coding Convensions

--------------------

i) File System Operations

j) Excel sheet Operations

k) database Operations

l) Other VB Script Objects
        i) Dictionary Object
        ii) Word
        iii) Internet Explorer Object
        iV) RegExp Object

m) Regular expressions

k) Error Handling

VB Script Variables
Definition 1):
Variable is a named memory location for storing program information
Definition 2):
A variable is a convenient placeholder that refers to a computer memory location where we can store program information that may change during the time our script is running.
Purpose of Variable:

a) Comparing values

Example:
Dim x,y,a
x=100
y=100
a=x=y
Msgbox a 'It returns True

b) Holding Program Result

Example:
Cost=Tickets*Price

c) Passing parameters

d) To store data that returned by functions
Example:
myDate=Now ‘ It returns current data & time

e) To hold data
Example:
myName=”gcreddy”

Declaring Variables

We declare variables explicitly in our script using the Dim statement, the Public statement, and the Private statement.
For example:
Dim city
Dim x
We declare multiple variables by separating each variable name with a comma. For
Example:
Dim x, y, city, gcreddy

We can also declare a variable implicitly by simply using its name in our script. That is not generally a good practice because we could misspell the variable name in one or more places, causing unexpected results when our 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 our script.


Option Explicit Statement

Forces explicit declaration of all variables in a script.

Option Explicit ' Force explicit variable declaration.
Dim MyVar ' Declare variable.
MyInt = 10 ' Undeclared variable generates error.
MyVar = 10 ' Declared variable does not generate error.
Naming Restrictions for Variables

Variable names follow the standard rules for naming anything in VBScript. A variable name:

a) Must begin with an alphabetic character.
Dim abc    'Right
Dim 9ab    'Wrong
Dim ab9    'Right

b) Cannot contain an embedded period.
Dim abc     'Right
Dim ab.c    'worng
Dim ab-c    'wrong
Dim ab c    'wrong
Dim ab_c   'Right

c) Must not exceed 255 characters.

d) Must be unique in the scope in which it is declared.
Scope of Variables

A variable's scope is determined by where we declare it.

When we declare a variable within a procedure, only code within that procedure can access or change the value of that variable.

If we declare a variable outside a procedure, we make it recognizable to all the procedures in our script. This is a script-level variable, and it has script-level scope.
Example:
Dim x,y,z
x=10
y=20
z=x+y
msgbox z    'Returns 30
Function res
   Dim a,b,c
   a=30
   b=40
   c=a+b+y
   msgbox c   ' Returns 90
End Function
Call res

Life Time of Variables

The lifetime of a variable depends on how long it exists.

The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running.

At procedure level, a variable exists only as long as you are in the procedure.
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:
A = 200
City = “Hyderabad”

X=100: Y=200
Scalar Variables and Array Variables

A variable containing a single value is a scalar variable.

A variable containing a series of values, is called an array variable.

Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses parentheses () following the variable name.

Example:
Dim A(3)

Although the number shown in the parentheses is 3, all arrays in VBScript are zero-based, so this array actually contains 4 elements.

We assign data to each of the elements of the array using an index into the array.
Beginning at zero and ending at 4, data can be assigned to the elements of an array as follows:

A(0) = 256
A(1) = 324
A(2) = 100
A(3) = 55

Similarly, the data can be retrieved from any element using an index into the particular array element you want.

For example:

SomeVariable = A(4)

Arrays aren't limited to a single dimension. We can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions.

In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns:

Dim MyTable(5, 10)

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.
Dynamic Arrays

We can also declare an array whose size changes during the time our script is running. This is called a dynamic array.

The array is initially declared within a procedure using either the Dim statement or using the ReDim statement.

However, for a dynamic array, no size or number of dimensions is placed inside the parentheses.

For example:
Dim MyArray()
ReDim AnotherArray()

To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension.

In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.

ReDim MyArray(25)

ReDim Preserve MyArray(30)

There is no limit to the number of times we can re size a dynamic array, although if we make an array smaller, we lose the data in the elimination
VB Script Data Types

What is Data Type?

Data type is a categorization of identifying one of various types of data, such as string, integer, double, date or Boolean etc…

Implicit & Explicit Data types:

Specifying Data types along with variable names is called Explicit declaration of Data types.

Declaring Variables Without specifying Data types is called Implicit declaration of variables.

VB Script Supports Implicit declaration of variables only, doesn’t support Explicit declaration of Data types.

VB Script Data Type:

VB script has only data type called Variant, it can hold any type of data, and based on usage of data it considers data sub types.

Example:

Dim x

X is a Variable and it can hold any type of data (String, integer, double, date etc…)

X= “G C Reddy” String type

X= 100 Integer

X= 10.345 Double

X=#10/10/2010# Date

 How to know Data sub types:

Using VarType Function we can get data sub type

VarType Function

It returns a value indicating a subtype of a Variable

Example:

'Checking Data sub types
-----------------------------
Dim x, y, z(3)
x="Gcreddy"
Msgbox VarType(x) '8 for String

x=500
Msgbox VarType(x) ' 2 for Integer

x="400"
Msgbox VarType(x) '8 for String

x=199.123
Msgbox VarType(x) '5 for double

x="199.123"
Msgbox VarType(x) '8 for string

x=#10/10/2010#
Msgbox VarType(x) '7 for date

Set x =CreateObject("Scripting.FileSystemObject")
Msgbox VarType(x) '9 for Automation Object

x=384322225
Msgbox VarType(x) 3 for Long integer

Msgbox VarType(z) 8204 for Array

Msgbox VarType(y) '0 for Empty / Uninitialized

-------------------------------------------------------------------------------------
Data sub type and descriptions:

String:

It consists of any type of characters, maximum length up to approximately 2 billion characters.

Boolean:
It Contains either True or False (Logical Result)

Empty:

Uninitialized, Value is 0 for numeric variables or a zero-length string ("") for string variables.

Integer:

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

Long Integer

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

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:

Contains a number that represents a date between January 1, 100 to December 31, 9999

Object:

Contains an object

Error:

Contains an error number

Null:

Contains no valid data

Etc…
------------------------------------------------------------------------------------


'Converting the Data from one type to another
-----------------------------------------------
We use Conversion Functions to convert the data from one type to another.

Whenever we read data using input devices, or from files, or from Databases or from Application objects then VB Script considers the data as string type data, we need to convert the data in order to perform operations.

Dim x, y, Tickets, Price
'Read from Input Devices
x=InputBox("Enter a Value")
Msgbox VarType(x) '8 for String
x=Cint(x)
Msgbox VarType(x) '2 for Integer

y=InputBox("Enter a Value")
Msgbox VarType(y) '8 for String
y=Cdbl(y)
Msgbox VarType(y) '5 for double

'Read from Application Objects

Tickets = Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText()
Msgbox VarType(Tickets)'8
Tickets=Cint(Tickets)
Msgbox VarType(Tickets) '2

Price = Window("Flight Reservation").WinEdit("Price:").GetVisibleText()
Msgbox VarType(Price) '8
Price=Cdbl(Price)
Msgbox VarType(Price) '5

----------------------------------------------------------------------
Example: 2
Dim a, b, c

a=”100”
Msgbox VarType(a) ‘ 8 for String

a=Cint(a)
Msgbox VarType(a) ‘2 for Integer

b=”100.345”
Msgbox VarType(b) ‘ 8 for String

b=Cdbl(b)
Msgbox VarType(b) ‘5 for Double

c=”Hyderabad”
Msgbox VarType(c) ‘8 for String

c=Cint(c)
Msgbox VarType(c) ‘Mismatch (Error)
Note: we can’t convert alphabets as integer or double type data
VB Script Data Types

What is Data Type?

Data type is a categorization of identifying one of various types of data, such as string, integer, double, date or Boolean etc…

Implicit & Explicit Data types:

Specifying Data types along with variable names is called Explicit declaration of Data types.

Declaring Variables Without specifying Data types is called Implicit declaration of variables.

VB Script Supports Implicit declaration of variables only, doesn’t support Explicit declaration of Data types.

VB Script Data Type:

VB script has only data type called Variant, it can hold any type of data, and based on usage of data it considers data sub types.

Example:

Dim x

X is a Variable and it can hold any type of data (String, integer, double, date etc…)

X= “G C Reddy” String type

X= 100 Integer

X= 10.345 Double

X=#10/10/2010# Date

 How to know Data sub types:

Using VarType Function we can get data sub type

VarType Function

It returns a value indicating a subtype of a Variable

Example:

'Checking Data sub types
-----------------------------
Dim x, y, z(3)
x="Gcreddy"
Msgbox VarType(x) '8 for String

x=500
Msgbox VarType(x) ' 2 for Integer

x="400"
Msgbox VarType(x) '8 for String

x=199.123
Msgbox VarType(x) '5 for double

x="199.123"
Msgbox VarType(x) '8 for string

x=#10/10/2010#
Msgbox VarType(x) '7 for date

Set x =CreateObject("Scripting.FileSystemObject")
Msgbox VarType(x) '9 for Automation Object

x=384322225
Msgbox VarType(x) 3 for Long integer

Msgbox VarType(z) 8204 for Array

Msgbox VarType(y) '0 for Empty / Uninitialized

-------------------------------------------------------------------------------------
Data sub type and descriptions:

String:

It consists of any type of characters, maximum length up to approximately 2 billion characters.

Boolean:
It Contains either True or False (Logical Result)

Empty:

Uninitialized, Value is 0 for numeric variables or a zero-length string ("") for string variables.

Integer:

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

Long Integer

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

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:

Contains a number that represents a date between January 1, 100 to December 31, 9999

Object:

Contains an object

Error:

Contains an error number

Null:

Contains no valid data

Etc…
------------------------------------------------------------------------------------


'Converting the Data from one type to another
-----------------------------------------------
We use Conversion Functions to convert the data from one type to another.

Whenever we read data using input devices, or from files, or from Databases or from Application objects then VB Script considers the data as string type data, we need to convert the data in order to perform operations.

Dim x, y, Tickets, Price
'Read from Input Devices
x=InputBox("Enter a Value")
Msgbox VarType(x) '8 for String
x=Cint(x)
Msgbox VarType(x) '2 for Integer

y=InputBox("Enter a Value")
Msgbox VarType(y) '8 for String
y=Cdbl(y)
Msgbox VarType(y) '5 for double

'Read from Application Objects

Tickets = Window("Flight Reservation").WinEdit("Tickets:").GetVisibleText()
Msgbox VarType(Tickets)'8
Tickets=Cint(Tickets)
Msgbox VarType(Tickets) '2

Price = Window("Flight Reservation").WinEdit("Price:").GetVisibleText()
Msgbox VarType(Price) '8
Price=Cdbl(Price)
Msgbox VarType(Price) '5

----------------------------------------------------------------------
Example: 2
Dim a, b, c

a=”100”
Msgbox VarType(a) ‘ 8 for String

a=Cint(a)
Msgbox VarType(a) ‘2 for Integer

b=”100.345”
Msgbox VarType(b) ‘ 8 for String

b=Cdbl(b)
Msgbox VarType(b) ‘5 for Double

c=”Hyderabad”
Msgbox VarType(c) ‘8 for String

c=Cint(c)
Msgbox VarType(c) ‘Mismatch (Error)
VB Script Operators

Operators are used for performing mathematical, comparison and logical operations.
VB Script has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.

We can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others.

Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.

Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear.

Arithmetic and logical operators are evaluated in the following order of precedence.

1)  Arithmetic Operators:

Operator Description
1) Exponentiation Operator (^) Raises a number to the power of an exponent

2) Multiplication Operator (*) Multiplies two numbers.

3) Division Operator (/) Divides two numbers and returns a floating-point 
result.

4) Integer Division Operator (\) Divides two numbers and returns an integer result.

5) Mod Operator Divides two numbers and returns only the remainder.

6) Addition Operator (+) Sums two numbers.

7) Subtraction Operator (-) Finds the difference between two numbers or indicates the negative value of a numeric expression.

8) Concatenation Operator (&) Forces string concatenation of two expressions.

Example:

Dim a,b,c
a=10
b=3
c=a^b
msgbox c '1000

c=a*b
msgbox c '30

c=a/b
msgbox c '3.33333333

c=a\b
msgbox c '3

c=a mod b
msgbox c '1

c=a-b
msgbox c '7

Dim a,b,c
a=10
b=2
c=3
d=c*a^b
'c=a+b
msgbox d '1000

Addition (+) operator

Dim a,b,c
a=10
b=2
c=a+b
msgbox c '12  (if both are numeric, then it adds)

a="10"
b=2
c=a+b
msgbox c '12  (one is string another numeric, then it adds)

a="10"
b="2"
c=a+b
msgbox c '102 (if both are strings, then it concatenates)

a="hydera"
b="bad"
c=a+b
msgbox c 'hyderabad

a="gagan"
b=2
c=a+b
msgbox c 'error

Concatenation Operator

Dim a,b,c
a=10
b=2
c=a&b
msgbox c '102

a="10"
b=2
c=a&b
msgbox c '102

a="10"
b="2"
c=a&b
msgbox c '102

a="hydera"
b="bad"
c=a&b
msgbox c '102

2) Comparison Operators

Used to compare expressions.

Operator Description
1) = (Equal to) Used to compare expressions.
2) <> (Not equal to) Used to compare expressions.
3) < Less than 4) > Grater than
5) <= Less than or equal to 6) >= Greater than or equal to
7) Is Object equivalence

Example:

Dim x,y,z
x=10
y=20
z=x=y
Msgbox z 'False

x=10
y=20
z=x>y
Msgbox z 'False

x=10
y=20
z=x>=y
Msgbox z 'False

x=10
y=20
z=x<>y
Msgbox z 'True

x=10
y=20
z=x<y
Msgbox z 'True

x=10
y=20
z=x<=y
Msgbox z 'True
3) Concatenation Operators

Operator Description
1) Addition Operator (+)

Sums two numbers
If Then
1) Both expressions are numeric Add.
2) Both expressions are strings Concatenate.
3) One expression is numeric and the other is a string Add.

2) Concatenation Operator (&) Forces string concatenation of two expressions.


4)  Logical Operators

Operator Description Syntax
1) Not Performs logical negation on an expression result= Not expression
2) And Performs a logical conjunction on two expressions. result= expression1 And expression2
3) Or Performs a logical disjunction on two expressions. result= expression1 Or expression2
4) Xor Performs a logical exclusion on two expressions. result= expression1 Xor expression2
5) Eqv Performs a logical equivalence on two expressions. result= expression1 Eqv expression2

6) Imp Performs a logical implication on two expressions. result= expression1 Imp expression2
 Input and Out Put Operations

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.

Example:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

Example:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
MyVar contains either 1 or 2, depending on which button is clicked.
VB Script Constants

A constant is a meaningful name that takes the place of a number or string and never changes.

 
Creating Constants

We create user-defined constants in VBScript using the Const statement. Using the Const statement, we can create string or numeric constants with meaningful names and assign them literal values.


Const statement


Declares constants for use in place of literal values.


Example:


Const MyString = "This is my string."

Const MyAge = 49

Const CutoffDate = #6-1-97#



Note that String literal is enclosed in quotation marks (" ").

Represent Date literals and time literals by enclosing them in number signs (#).

We declare multiple constants by separating each constant name and value with a comma. For example:

Const price= 100, city= “Hyderabad”, x= 27
Flow Control (Conditional Statements)

We can control the flow of our script with conditional statements and looping statements.

Using conditional statements, we can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript:

1) If…Then…Else Statement
2) Select Case Statement
Making Decisions Using If...Then...Else

The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run.

Usually the condition is an expression that uses a comparison operator to compare one value or variable with another.

If...Then...Else statements can be nested to as many levels as you need.
1)  Running a Statement if a Condition is True (single statement)

To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement.

Dim myDate
myDate = #2/13/98#
If myDate < Now Then myDate = Now

2)  Running Statements if a Condition is True (multiple statements)
To run more than one line of code, we must use the multiple-line (or block) syntax. This syntax includes the End If statement.

Dim x
x= 20
If x>10 Then

msgbox "x value is: "&x
msgbox "Bye Bye"
End If

3) Running Certain Statements if a Condition is True and Running Others if a Condition is False

We can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.

Example:

Dim x
x= Inputbox (" Enter a value")
If x>100 Then
Msgbox "Hello G.C.Reddy"
Msgbox "X is a Big Number"
Msgbox "X value is: "&X
Else
Msgbox "GCR"
Msgbox "X is a Small Number"
Msgbox "X value is: "&X
End If
4)  Deciding Between Several Alternatives

A variation on the If...Then...Else statement allows us to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so we can control program flow based on different possibilities.

Example:
Dim x
x= Inputbox (" Enter a value")


If x>0 and x<=100 Then
Msgbox "Hello G.C.Reddy"
Msgbox "X is a Small Number"
Msgbox "X value is "&x

Else IF x>100 and x<=500 Then
Msgbox "Hello GCR"
Msgbox "X is a Medium Number"

Else IF x>500 and x<=1000 Then
Msgbox "Hello Chandra Mohan Reddy"
Msgbox "X is a Large Number"

Else
Msgbox "Hello Sir"
Msgbox "X is a Grand Number"
End If
End If
End If
5) Executing a certain block of statements when two / more conditions are True (Nested If...)

Example:

Dim State, Region
State=Inputbox ("Enter a State")
Region=Inputbox ("Enter a Region")

If state= "AP" Then
If Region= "Telangana" Then
msgbox "Hello G.C.Reddy"
msgbox "Dist count is 10"

Else if Region= "Rayalasema" Then
msgbox "Hello GCR"
msgbox "Dist count is 4"

Else If Region= "Costal" Then
msgbox "Hello Chandra mohan Reddy"
msgbox "Dist count is 9"

End If
End If
End If
End If
Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.
Example:

Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")

Select Case Operation

Case "add"
Result= cdbl (x)+cdbl (y)
Msgbox "Hello G.C.Reddy"
Msgbox "Addition of x,y values is "&Result

Case "sub"
Result= x-y
Msgbox "Hello G.C.Reddy"
Msgbox "Substraction of x,y values is "&Result

Case "mul"
Result= x*y
Msgbox "Hello G.C.Reddy"
Msgbox "Multiplication of x,y values is "&Result

Case "div"
Result= x/y
Msgbox "Hello G.C.Reddy"
Msgbox "Division of x,y values is "&Result

Case "mod"
Result= x mod y
Msgbox "Hello G.C.Reddy"
Msgbox "Mod of x,y values is "&Result

Case "expo"
Result= x^y
Msgbox "Hello G.C.Reddy"
Msgbox"Exponentation of x,y values is "&Result

Case Else
Msgbox "Hello G.C.Reddy"
msgbox "Wrong Operation"

End Select
Flow Control (Loop Statements)

o Looping allows us to run a group of statements repeatedly.
o Some loops repeat statements until a condition is False;
o Others repeat statements until a condition is True.
o There are also loops that repeat statements a specific number of times.
The following looping statements are available in VBScript:
o Do...Loop: Loops while or until a condition is True.
o While...Wend: Loops while a condition is True.
o For...Next: Uses a counter to run statements a specified number of times.
o For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.
1) Using Do Loops

We can use Do...Loop statements to run a block of statements an indefinite number of times.

The statements are repeated either while a condition is True or until a condition becomes True.
a)  Repeating Statements While a Condition is True

Repeats a block of statements while a condition is True or until a condition becomes True

i) Do While condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:

Example:

Dim x
Do While x<5 x=x+1
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
Loop

ii) Do
Statements
-----------
-----------
Loop While condition


Example:

Dim x
x=1
Do
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
b)  Repeating a Statement Until a Condition Becomes True

iii) Do Until condition
Statements
-----------
-----------
Loop
Or, we can use this below syntax:
Example:

Dim x
Do Until x=5 x=x+1
Msgbox "G.C.Reddy"
Msgbox "Hello QTP"
Loop

Or, we can use this below syntax:

iv) Do
Statements
-----------
-----------
Loop Until condition
Or, we can use this below syntax:

Example:

Dim x
x=1
Do
Msgbox “Hello G.C.Reddy”
Msgbox "Hello QTP"
x=x+1
Loop Until x=5
2 While...Wend Statement

Executes a series of statements as long as a given condition is True.

Syntax:
While condition
Statements
-----------
-----------
Wend

Example:

Dim x
x=0
While x<5 x=x+1
msgbox "Hello G.C.Reddy"
msgbox "Hello QTP"
Wend
3)  For...Next Statement

Repeats a group of statements a specified number of times.
Syntax:
For counter = start to end [Step step]
statements
Next

Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello G.C.Reddy"
Next
4)  For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

Syntax:

For Each item In array
Statements
Next

Example: (1

Dim a,b,x (3)
a=20
b=30
x(0)= "Addition is "& a+b
x(1)="Substraction is " & a-b
x(2)= "Multiplication is " & a*b
x(3)= "Division is " & a/b

For Each element In x
msgbox element
Next

Example: (2

MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
User Defined Functions

In VBScript, there are two kinds of procedures available; the Sub procedure and the Function procedure.

1)  Sub Procedures

A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value.

A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure).

If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

Syntax:
Sub Procedure name ()
Statements
-----------
-----------
End Sub
Or
Sub Procedure name (argument1, argument2)
Statements
-----------
-----------
End Sub

Example: 1

Sub ConvertTemp()
temp = InputBox("Please enter the temperature in degrees F.", 1)
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Example: 2

2)  Function Procedures

A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements.

A Function procedure is similar to a Sub procedure, but can also return a value.

A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure).

If a Function procedure has no arguments, its Function statement must include an empty set of parentheses.

A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.
Syntax:
Function Procedure name ()
Statements
-----------
-----------
End Function
Or
Function Procedure name (argument1, argument2)
Statements
-----------
-----------
End Function

Example: 1

Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

Example: 2

Function cal(a,b,c)
cal = (a+b+c)
End Function

3)  Getting Data into and out of Procedures

o Each piece of data is passed into our procedures using an argument.
o Arguments serve as placeholders for the data we want to pass into our procedure. We can name our arguments any valid variable name.
o When we create a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure.
o Any arguments are placed inside these parentheses, separated by commas.

4)  Using Sub and Function Procedures in Code

A Function in our code must always be used on the right side of a variable assignment or in an expression.

For example:
Temp = Celsius(fDegrees)
-Or-
MsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma.

The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.

Call MyProc(firstarg, secondarg)

MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't used.

5) Examples:

(here, I used Flight Reservation Application for creating Functions, why because, It is the default application for QTP, anybody can practice easily...G C Reddy)

'*******************************************
'        Login Operation
'*******************************************
Function Login(Agent,Pwd)
   SystemUtil.Run "C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe"
    Dialog("Login").Activate
    Dialog("Login").WinEdit("Agent Name:").Set Agent
    Dialog("Login").WinEdit("Password:").Set Pwd
    Dialog("Login").WinButton("OK").Click

    If Window("Flight Reservation").Exist(10) Then
        Login="Login Operation Sucessful"
        'Msgbox Login
        else
Login="Login Operation Unsucessful"
        Dialog("Login").Dialog("Flight Reservations").WinButton("OK").Click
        Dialog("Login").WinButton("Cancel").Click
        'Msgbox Login
End If
End Function

'***************************************
'        Closing Application
'***************************************
Function Close_App()
if Window("Flight Reservation").Exist(3) Then
Window("Flight Reservation").Close
End If
End Function

'***************************************
'        Open Order
'***************************************
Function Open_Order(ord)
   ordnum=0
   On Error Resume Next
Window("Flight Reservation").Activate
Window("Flight Reservation").WinButton("Button").Click
Window("Flight Reservation").Dialog("Open Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open Order").WinEdit("Edit").Set ord
Window("Flight Reservation").Dialog("Open Order").WinButton("OK").Click
ordnum=Window("Flight Reservation").WinEdit("Order No:").GetROProperty ("text")
ordnum=cdbl (ordnum)
If  ord=ordnum Then
    Open_Order= "Order Number "&ordnum&" Opened Sucuessfully"
    'Msgbox Open_Order
    else
Open_Order= "Order Number "&ordnum&" Not Opened/ Not Available"
Window("Flight Reservation").Dialog("Open Order").Dialog("Flight Reservations").WinButton("OK").Click
Window("Flight Reservation").Dialog("Open Order").WinButton("Cancel").Click
    'Msgbox Open_Order
End If
End Function

'******************************************
'        Update Order
'******************************************
Function Update_Order(Tickets)
Window("Flight Reservation").Activate
Window("Flight Reservation").WinEdit("Tickets:").Set Tickets
Window("Flight Reservation").WinButton("Update Order").Click
wait(10)
update=Window("Flight Reservation").ActiveX("Threed Panel Control").GetROProperty ("text")
If update="Update Done..." Then
Update_Order= "Order Updated Sucussfully"
'Msgbox Update_Order
Else
Window("Flight Reservation").Dialog("Flight Reservations").WinButton("OK").Click
Update_Order= "Order Not Updated"
'Msgbox Update_Order
End If
End Function

'******************************************
'                  Function to send a mail 
'******************************************
Function SendMail(SendTo, Subject, Body, Attachment) 
Set otl=CreateObject("Outlook.Application")
Set m=otl.CreateItem(0) 
m.to=SendTo 
m.Subject=Subject 
m.Body=Body 
If (Attachment <> "") Then 
Mail.Attachments.Add(Attachment)
End If
m.Send 
otl.Quit 
Set m = Nothing 
Set otl = Nothing
End Function

Call SendMail("gcreddy@gcreddy.com","hi","This is test mail for testing","")
 Types of Errors in VBScript

 Generally Errors in VB Script are 2 Types

1) VB Script Run-time Errors

VB Script run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable expressions are being evaluated, and memory is being dynamic allocated.

Error Number Description:

429 ActiveX component can't create object
507 An exception occurred
449  Argument not optional
17   Can't perform requested operation
430 Class doesn't support Automation
506 Class not defined
11  Division by zero
48    Error in loading DLL
5020 Expected ')' in regular expression
5019 Expected ']' in regular expression
432  File name or class name not found during Automation operation
92   For loop not initialized
5008 Illegal assignment
51   Internal error
505 Invalid or unqualified reference
481 Invalid picture
5    Invalid procedure call or argument
5021 Invalid range in character set
94    Invalid use of Null
448  Named argument not found
447 Object doesn't support current locale setting
445 Object doesn't support this action
438 Object doesn't support this property or method
451 Object not a collection
504 Object not safe for creating
503 Object not safe for initializing
502 Object not safe for scripting
424 Object required
91 Object variable not set
7  Out of Memory
28 Out of stack space
14 Out of string space
6   Overflow
35 Sub or function not defined
9  Subscript out of range
5017 Syntax error in regular expression
462 The remote server machine does not exist or is unavailable
10 This array is fixed or temporarily locked
13 Type mismatch
5018 Unexpected quantifier
500 Variable is undefined
458 Variable uses an Automation type not supported in VBScript
450 Wrong number of arguments or invalid property assignment

2) VB Script Syntax Errors

VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the program compilation stage, before the program has begun to be executed.

Error Number Description:

1052 Cannot have multiple default property/method in a Class
1044 Cannot use parentheses when calling a Sub
1053 Class initialize or terminate do not have arguments
1058 'Default' specification can only be on Property Get
1057 'Default' specification must also specify 'Public'
1005 Expected '('
1006 Expected ')'
1011 Expected '='
1021 Expected 'Case'
1047 Expected 'Class'
1025 Expected end of statement
1014 Expected 'End'
1023 Expected expression
1015 Expected 'Function'
1010 Expected identifier
1012 Expected 'If'
1046 Expected 'In'
1026 Expected integer constant
1049 Expected Let or Set or Get in property declaration
1045 Expected literal constant
1019 Expected 'Loop'
1020 Expected 'Next'
1050 Expected 'Property'
1022 Expected 'Select'
1024 Expected statement
1016 Expected 'Sub'
1017 Expected 'Then'
1013 Expected 'To'
1018 Expected 'Wend'
1027 Expected 'While' or 'Until'
1028 Expected 'While,' 'Until,' or end of statement
1029 Expected 'With'
1030 Identifier too long
1014 Invalid character
1039 Invalid 'exit' statement
1040 Invalid 'for' loop control variable
1013 Invalid number
1037 Invalid use of 'Me' keyword
1038 'loop' without 'do'
1048 Must be defined inside a Class
1042 Must be first statement on the line
1041 Name redefined
1051 Number of arguments must be consistent across properties specification
1001 Out of Memory
1054 Property Set or Let must have at least one argument
1002 Syntax error
1055 Unexpected 'Next'
1015 Unterminated string constant
Built-In Functions of VB Script

o Conversions (25)

o Dates/Times (19)

o Formatting Strings (4)

o Input/Output (3)

o Math (9)

o Miscellaneous (3)

o Rounding (5)

o Strings (30)

o Variants (8)

Important Functions


1) Abs Function
Returns the absolute value of a number.

Dim num
num=abs(-50.33)
msgbox num

2) Array Function
Returns a variant containing an Array

Dim A
A=Array("hyderabad","chennai","mumbai")
msgbox A(0)
ReDim A(5)
A(4)="nellore"
msgbox A(4)

3) Asc Function
Returns the ANSI character code corresponding to the first letter in a string.

Dim num
num=Asc("A")
msgbox num
* It returns the value 65 *

4) Chr Function
Returns the character associated with the specified ANSI character code.

Dim char
Char=Chr(65)
msgbox char
* It returns A *

5) CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.

Dim num
num=123.45
myInt=CInt(num)
msgbox MyInt

6) Date Function
Returns the Current System Date.

Dim mydate
mydate=Date
msgbox mydate

7) Day Function
Ex1) Dim myday
myday=Day("17,December,2009")
msgbox myday

Ex2) Dim myday
mydate=date
myday=Day(Mydate)
msgbox myday

8) DateDiff Function
Returns the number of intervals between two dates.

Dim Date1, Date2, x

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("yyyy", Date1, Date2)
Msgbox x 'Differnce in Years

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("q", Date1, Date2)
Msgbox x 'Differnce in Quarters

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("m", Date1, Date2)
Msgbox x 'Differnce in Months

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("w", Date1, Date2)
Msgbox x 'Differnce in weeks

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("d", Date1, Date2)
Msgbox x 'Differnce in days

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("h", Date1, Date2)
Msgbox x 'Differnce in Hours

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("n", Date1, Date2)
Msgbox x 'Differnce in Minutes

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("s", Date1, Date2)
Msgbox x 'Differnce in Seconds

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("y", Date1, Date2)
Msgbox x  'Differnce in day of years

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("a", Date1, Date2)
Msgbox x 'Error

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff(Date1, Date2)
Msgbox x 'Error

9) Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Dim mytime, Myhour
mytime=Now
myhour=hour (mytime)
msgbox myhour

10) Join Function
Returns a string created by joining a number of substrings contained in an array.

Dim mystring, myarray(3)
myarray(0)="Chandra "
myarray(1)="Mohan "
myarray(2)="Reddy"
mystring=Join(MyArray)
msgbox mystring

11) Eval Function

Evaluates an expression and returns the result.

12) Time Function
Returns a Variant of subtype Date indicating the current system time.

Dim mytime
mytime=Time
msgbox mytime

13) VarType Function

Returns a value indicating the subtype of a variable.

Dim x,y
x=100
y=VarType(x)
Msgbox y '2 (Integer)

x="Hyderabad"
y=VarType(x)
Msgbox y '8 (String)

x=#10-10-10#
y=VarType(x)
Msgbox y '7(Date format)

x=100.56
y=VarType(x)
Msgbox y ' 5(Double)


y=VarType(a)
Msgbox y '0 (Empty)

Set x =CreateObject("Scripting.FileSystemObject")
y=VarType(x)
Msgbox y '9(Automation Object)

14) Left Function

Dim Val, x,y
Val="Hyderabad"
x=Left(Val,3)
Msgbox x 'Hyd

Val=100
x=Left(Val,1)
Msgbox x '1

Val="Hyderabad"
x=Left(Val,0)
Msgbox x 'Null

Val="Hyderabad"
x=Left(Val,12)
Msgbox x 'Hyderabad

Val=#10-10-10#
x=Left(Val,3)
Msgbox x '10/

Val="Hyderabad"
x=Left(Val)
Msgbox x 'Error (Lengnth is Manditory)
14) Right Function
Dim AnyString, MyStr
AnyString = "Hello World" ' Define string.
MyStr = Right(AnyString, 1) ' Returns "d".
MyStr = Right(AnyString, 6) ' Returns " World".
MyStr = Right(AnyString, 20) ' Returns "Hello World".

15) Len Function
Returns the number of characters in a string or the number of bytes required to store a variable.

Ex 1):
Dim Mystring
mystring=Len("G.C.Reddy")
msgbox mystring

Ex 2):
Dim Mystring
Mystring=Inputbox("Enter a Value")
Mystring=Len(Mystring)
Msgbox Mystring

16) Mid Function
Returns a specified number of characters from a string.

Dim Val, x,y
Val="Hyderabad"
x=Mid(Val,3,4)
Msgbox x 'dera

Val=100
x=Mid(Val,1)
Msgbox x '100

Val="Hyderabad"
x=Mid(Val,6,7)
Msgbox x 'abad

Val="Hyderabad"
x=Mid(Val,6,1)
Msgbox x 'a

Val="Hyderabad"
x=Mid(Val,6,0)
Msgbox x 'Null

Val="Hyderabad"
x=Mid(Val,12)
Msgbox x 'Null

Val=#10-10-10#
x=Mid(Val,3,3)
Msgbox x '/10

Val=#2010-10-10#
x=Mid(Val,5)
Msgbox x '/2010

Val="Hyderabad"
x=Mid(Val)
Msgbox x 'Error

17) Timer Function
Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Function myTime(N)
Dim StartTime, EndTime
StartTime = Timer
For I = 1 To N
Next
EndTime = Timer
myTime= EndTime - StartTime
msgbox myTime
End Function
Call myTime(2000)

17) isNumeric Function

Dim MyVar, MyCheck
MyVar = 53
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
MyVar = "459.95"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
MyVar = "45 Help"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
* It Returns True/False like Result *

18) 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.

Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

19) Msgbox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")

20) CreateObject

creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system

Set objFso=createobject ("Scripting.FileSystemObject")

'creates and returns reference of  the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (Ms-Excel files)

Set objExcel = CreateObject("Excel.Application")

'creates and returns reference of  the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents

Set objWord = CreateObject("Word.Application")

'creates and returns reference of  the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases

Set objConnection = CreateObject("ADODB.Connection")


'creates and returns reference of  the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records)

Set objRecordSet = CreateObject("ADODB.Recordset")

'creates and returns reference of  the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations

Set objPPT = CreateObject("PowerPoint.Application")

Set xmldoc = WScript.CreateObject("msxml2.domdocument")

21) Round

Returns a number rounded to a specified number of decimal places.

Dim num
num=172.499
num=Round(num)
msgbox num

22) StrReverse
It returns reverse value of the given sring
x=strreverse ("dabaraedyh")
msgbox x

23) strComp
It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd)
Dim x, y
x="cd": y="bcd"
comp=strcomp(x,y)
msgbox comp

24) Replace
It replace a sub string with given value (another sub string)
mystring=Replace("kb script", "k","v")
msgbox mystring
Conversion Functions

1) Asc Function

Returns the ANSI character code corresponding to the first letter in a string.
Syntax:
Asc(string)
Remarks

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.
Dim MyNumber
MyNumber = Asc("A")       ' Returns 65.
MyNumber = Asc("a")       ' Returns 97.
MyNumber = Asc("Apple")   ' Returns 65.

2) CByte Function

Returns an expression that has been converted to a Variant of subtype Byte.
Syntax:

CByte(expression)
The expression argument is any valid expression.
Use the CByte function to provide conversions from any data type to a Byte subtype.
Example:
Dim MyDouble, MyByte
MyDouble = 125.5678        ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.

3) CDate Function
Returns an expression that has been converted to a Variant of subtype Date.
Syntax:
CDate(date)
The date argument is any valid date expression.
Use the IsDate function to determine if date can be converted to a date or time.
Example:

MyDate = "October 19, 1962"   ' Define date.
MyShortDate = CDate(MyDate)   ' Convert to Date data type.
MyTime = "4:35:47 PM"         ' Define time.
MyShortTime = CDate(MyTime)   ' Convert to Date data type.

4) Chr Function

Returns the character associated with the specified ANSI character code.
Syntax:

Chr(charcode)

The charcode argument is a number that identifies a character.
Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.
Example:
Dim MyChar

' Returns A:
MyChar = Chr(65)  
' Returns B:
MyChar = Chr(66)  
' Returns Z:
MyChar = Chr(90)  

' Returns a:
MyChar = Chr(97)  
' Returns b:
MyChar = Chr(98)  
' Returns z:
MyChar = Chr(122) 

' Returns 0:
MyChar = Chr(48)  
' Returns 1:
MyChar = Chr(49)  
' Returns 9:
MyChar = Chr(57)  

' Returns horizontal tab:
MyChar = Chr(9)
' Returns >:
MyChar = Chr(62)  
' Returns %:
MyChar = Chr(37)  

5) CLng Function
Returns an expression that has been converted to a Variant of subtype Long.
Syntax:

CLng(expression)

The expression argument is any valid expression.
Use the CLng function to provide conversions from any data type to a Long subtype.
Example:
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55   ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)   ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)   ' MyLong2 contains 25428.

6) CStr Function

Returns an expression that has been converted to a Variant of subtype String.
Syntax:
CStr(expression)

The expression argument is any valid expression.
Example:
Dim MyDouble, MyString
MyDouble = 437.324         ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324"

7) Oct Function

Returns a string representing the octal value of a number.
Syntax:
Oct(number)

The number argument is any valid expression.
Example:
Dim MyOct
MyOct = Oct(4)     ' Returns 4.
MyOct = Oct(8)     ' Returns 10.
MyOct = Oct(459)   ' Returns 713.

8) CBool Function

Returns an expression that has been converted to a Variant of subtype Boolean.
Synta:
CBool(expression)

The expression argument is any valid expression.
If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.
Example:
Dim A, B, Check
A = 5: B = 5           ' Initialize variables.
Check = CBool(A = B)   ' Check contains True.
A = 0                  ' Define variable.
Check = CBool(A)       ' Check contains False.

9) CCur Function

Returns an expression that has been converted to a Variant of subtype Currency.
Syntax:
CCur(expression)
The expression argument is any valid expression.
Example:
Dim MyDouble, MyCurr
MyDouble = 543.214588         ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2)   ' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292).

10) CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.
Syntax:
CInt(expression)
The expression argument is any valid expression.
Example:

Dim MyDouble, MyInt
MyDouble = 2345.5678     ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.

11) CSng Function

Returns an expression that has been converted to a Variant of subtype Single.
Syntax:
CSng(expression)

The expression argument is any valid expression.
Example:
Dim MyDouble1, MyDouble2, MySingle1, MySingle2   ' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)   ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)   ' MySingle2 contains 75.34216.

12) Hex Function

Returns a string representing the hexadecimal value of a number.
Syntax:
Hex(number)
number argument is any valid expression.
we can represent hexadecimal numbers directly by preceding numbers in the proper range with &H.
Example:
Dim MyHex
MyHex = Hex(5)   ' Returns 5.
MyHex = Hex(10)   ' Returns A.
MyHex = Hex(459)   ' Returns 1CB.
Built-In Functions of VB Script

o Conversions (25)

o Dates/Times (19)

o Formatting Strings (4)

o Input/Output (3)

o Math (9)

o Miscellaneous (3)

o Rounding (5)

o Strings (30)

o Variants (8)

Important Functions


1) Abs Function
Returns the absolute value of a number.

Dim num
num=abs(-50.33)
msgbox num

2) Array Function
Returns a variant containing an Array

Dim A
A=Array("hyderabad","chennai","mumbai")
msgbox A(0)
ReDim A(5)
A(4)="nellore"
msgbox A(4)

3) Asc Function
Returns the ANSI character code corresponding to the first letter in a string.

Dim num
num=Asc("A")
msgbox num
* It returns the value 65 *

4) Chr Function
Returns the character associated with the specified ANSI character code.

Dim char
Char=Chr(65)
msgbox char
* It returns A *

5) CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.

Dim num
num=123.45
myInt=CInt(num)
msgbox MyInt

6) Date Function
Returns the Current System Date.

Dim mydate
mydate=Date
msgbox mydate

7) Day Function
Ex1) Dim myday
myday=Day("17,December,2009")
msgbox myday

Ex2) Dim myday
mydate=date
myday=Day(Mydate)
msgbox myday

8) DateDiff Function
Returns the number of intervals between two dates.

Dim Date1, Date2, x

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("yyyy", Date1, Date2)
Msgbox x 'Differnce in Years

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("q", Date1, Date2)
Msgbox x 'Differnce in Quarters

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("m", Date1, Date2)
Msgbox x 'Differnce in Months

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("w", Date1, Date2)
Msgbox x 'Differnce in weeks

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("d", Date1, Date2)
Msgbox x 'Differnce in days

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("h", Date1, Date2)
Msgbox x 'Differnce in Hours

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("n", Date1, Date2)
Msgbox x 'Differnce in Minutes

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("s", Date1, Date2)
Msgbox x 'Differnce in Seconds

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("y", Date1, Date2)
Msgbox x  'Differnce in day of years

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff("a", Date1, Date2)
Msgbox x 'Error

Date1=#10-10-09#
Date2=#10-10-11#
x=DateDiff(Date1, Date2)
Msgbox x 'Error

9) Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Dim mytime, Myhour
mytime=Now
myhour=hour (mytime)
msgbox myhour

10) Join Function
Returns a string created by joining a number of substrings contained in an array.

Dim mystring, myarray(3)
myarray(0)="Chandra "
myarray(1)="Mohan "
myarray(2)="Reddy"
mystring=Join(MyArray)
msgbox mystring

11) Eval Function

Evaluates an expression and returns the result.

12) Time Function
Returns a Variant of subtype Date indicating the current system time.

Dim mytime
mytime=Time
msgbox mytime

13) VarType Function

Returns a value indicating the subtype of a variable.

Dim x,y
x=100
y=VarType(x)
Msgbox y '2 (Integer)

x="Hyderabad"
y=VarType(x)
Msgbox y '8 (String)

x=#10-10-10#
y=VarType(x)
Msgbox y '7(Date format)

x=100.56
y=VarType(x)
Msgbox y ' 5(Double)


y=VarType(a)
Msgbox y '0 (Empty)

Set x =CreateObject("Scripting.FileSystemObject")
y=VarType(x)
Msgbox y '9(Automation Object)

14) Left Function

Dim Val, x,y
Val="Hyderabad"
x=Left(Val,3)
Msgbox x 'Hyd

Val=100
x=Left(Val,1)
Msgbox x '1

Val="Hyderabad"
x=Left(Val,0)
Msgbox x 'Null

Val="Hyderabad"
x=Left(Val,12)
Msgbox x 'Hyderabad

Val=#10-10-10#
x=Left(Val,3)
Msgbox x '10/

Val="Hyderabad"
x=Left(Val)
Msgbox x 'Error (Lengnth is Manditory)
14) Right Function
Dim AnyString, MyStr
AnyString = "Hello World" ' Define string.
MyStr = Right(AnyString, 1) ' Returns "d".
MyStr = Right(AnyString, 6) ' Returns " World".
MyStr = Right(AnyString, 20) ' Returns "Hello World".

15) Len Function
Returns the number of characters in a string or the number of bytes required to store a variable.

Ex 1):
Dim Mystring
mystring=Len("G.C.Reddy")
msgbox mystring

Ex 2):
Dim Mystring
Mystring=Inputbox("Enter a Value")
Mystring=Len(Mystring)
Msgbox Mystring

16) Mid Function
Returns a specified number of characters from a string.

Dim Val, x,y
Val="Hyderabad"
x=Mid(Val,3,4)
Msgbox x 'dera

Val=100
x=Mid(Val,1)
Msgbox x '100

Val="Hyderabad"
x=Mid(Val,6,7)
Msgbox x 'abad

Val="Hyderabad"
x=Mid(Val,6,1)
Msgbox x 'a

Val="Hyderabad"
x=Mid(Val,6,0)
Msgbox x 'Null

Val="Hyderabad"
x=Mid(Val,12)
Msgbox x 'Null

Val=#10-10-10#
x=Mid(Val,3,3)
Msgbox x '/10

Val=#2010-10-10#
x=Mid(Val,5)
Msgbox x '/2010

Val="Hyderabad"
x=Mid(Val)
Msgbox x 'Error

17) Timer Function
Returns the number of seconds that have elapsed since 12:00 AM (midnight).

Function myTime(N)
Dim StartTime, EndTime
StartTime = Timer
For I = 1 To N
Next
EndTime = Timer
myTime= EndTime - StartTime
msgbox myTime
End Function
Call myTime(2000)

17) isNumeric Function

Dim MyVar, MyCheck
MyVar = 53
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
MyVar = "459.95"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
MyVar = "45 Help"
MyCheck = IsNumeric(MyVar)
msgbox MyCheck
* It Returns True/False like Result *

18) 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.

Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

19) Msgbox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")

20) CreateObject

creates and returns reference of the filesytemobject to an Automation object. It can be used for performing operations on computer file system

Set objFso=createobject ("Scripting.FileSystemObject")

'creates and returns reference of  the Excel bject to an Automation object. It can be used for performing operations on Spreed sheet (Ms-Excel files)

Set objExcel = CreateObject("Excel.Application")

'creates and returns reference of  the Word Object to an Automation object. It can be used for performing operations on Ms-Word documents

Set objWord = CreateObject("Word.Application")

'creates and returns reference of  the Database Connection to an Automation object. It can be used for Connecting, opening and Closing databases

Set objConnection = CreateObject("ADODB.Connection")


'creates and returns reference of  the Database Recordset to an Automation object. It can be used for performing operations on database tables(Records)

Set objRecordSet = CreateObject("ADODB.Recordset")

'creates and returns reference of  the Ms-Power point object to an Automation object. It can be used for performing operations on Power point presentations

Set objPPT = CreateObject("PowerPoint.Application")

Set xmldoc = WScript.CreateObject("msxml2.domdocument")

21) Round

Returns a number rounded to a specified number of decimal places.

Dim num
num=172.499
num=Round(num)
msgbox num

22) StrReverse
It returns reverse value of the given sring
x=strreverse ("dabaraedyh")
msgbox x

23) strComp
It compares two strings based on ASCII Values and Returens -1 (1st less than 2nd ), 0 (Equal) and 1 (1st greater than 2nd)
Dim x, y
x="cd": y="bcd"
comp=strcomp(x,y)
msgbox comp

24) Replace
It replace a sub string with given value (another sub string)
mystring=Replace("kb script", "k","v")
msgbox mystring
User Defined Functions

----------------------------------------------------------

i) Launching Application

Navigation:
a) Launch the Browser
b) Enter / Select the URL (“www.jjperfumes.com”)
Verification: Capture the Browser Name and Verify
—————
Function Launch_App()
SystemUtil.Run “C:\Program Files\Internet Explorer\IEXPLORE.EXE”,”",”C:\Documents and Settings\Administrator”,”open”
Browser(“Google”).Page(“Google”).Sync
Browser(“Google”).Navigate “http://www.jjperfumes.com/”
Wait (8)
Browser_Name = Browser(“Google”).GetROProperty(“title”)
If  Browser_Name=”JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online”  Then
Launch_App=”Jjperumes.com Browser Launched Sucessfully”
Msgbox Launch_App
Else
Launch_App=”Jjperumes.com Browser Not Launched”
Msgbox Launch_App
End If
End Function
——————————————————————————————–

ii) Customer Registration

Pre-Setup: Launching Application
Navigation:
a) Select Registration Link in     jjperfumes.com homepage
b) Enter all Mandatory details
c) Select Submit button
Verify: Capture confirmation Message and Verify
Function Register(Email)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume”).Link(“Register”).Click
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebList(“usertype”).Select “Retailer”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“firstname”).Set “dfgdg”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“lastname”).Set “dgdfgdfg”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebList(“gender”).Select “Male”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“address1″).Set “dfgfdgf”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“phone”).Set “9222222223″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“email”).Set Email
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“city”).Set “chennai”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebList(“state”).Select “MS – MISSISSIPPI”
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“zip”).Set “23456″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“password”).SetSecure “3c30bbc7daa0dccb83c2941bb87fa0709d34″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“conPass”).SetSecure “3c30bbcdb1f7a32d27a56f70a60f7d1e4159″
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebButton(“Submit”).Click
Wait (5)
Confirm_Message = Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_3″).WebElement(“Registered successfully.”).GetROProperty(“innertext”)
If  Confirm_Message=”Registered successfully. “Then
Register=”Customer Registration Sucessful”
Msgbox Register
Else
Register=”Registration Failed”
Msgbox Register
End If
End Function
——————-
Function Register(Email)
Set myBrowser=Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume”).Link(“Register”).Click
myBrowser.WebList(“usertype”).Select “Retailer”
myBrowser.WebEdit(“firstname”).Set “dfgdg”
myBrowser.WebEdit(“lastname”).Set “dgdfgdfg”
myBrowser.WebList(“gender”).Select “Male”
myBrowser.WebEdit(“address1″).Set “dfgfdgf”
myBrowser.WebEdit(“phone”).Set “9222222223″
myBrowser.WebEdit(“email”).Set Email
myBrowser.WebEdit(“city”).Set “chennai”
myBrowser.WebList(“state”).Select “MS – MISSISSIPPI”
myBrowser.WebEdit(“zip”).Set “23456″
myBrowser.WebEdit(“password”).SetSecure “3c30bbc7daa0dccb83c2941bb87fa0709d34″
myBrowser.WebEdit(“conPass”).SetSecure “3c30bbcdb1f7a32d27a56f70a60f7d1e4159″
myBrowser.WebButton(“Submit”).Click
Wait (5)
Confirm_Message = Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_3″).WebElement(“Registered successfully.”).GetROProperty(“innertext”)
If  Confirm_Message=”Registered successfully. “Then
Register=”Customer Registration Sucessful”
Msgbox Register
Else
Register=”Registration Failed”
Msgbox Register
End If
End Function

iii) Login Operation

Pre-Requisites:
a) Launching Application
b) Customer Registration
Navigation:
a) Select “Login” Link in jjperfumes.com homepage
b) Enter Email and Password
c) Select “Login Button”

Verify:
Check existence of LogOut Link
—————–
Function Login(Email, Pwd)
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume”).Link(“Login”).Click
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“username”).Set Email
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebEdit(“password”).Set Pwd
Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_2″).WebButton(“Login”).Click
If Browser(“JJ Perfumes-Discount perfume”).Page(“JJ Perfumes-Discount perfume_3″).Link(“Logout”).Exist(10) Then
Login=”Login Operation Sucessful”
Msgbox Login
Else
Login=”Login Failed”
Msgbox Login
End If
End Function

iv) Closing Application

————————
Navigation:
————
a) Check the Existence of jjperfumes.com Browser
b) Close the Browser window (If exists)
—————–
Function Launch_App()
SystemUtil.Run “C:\Program Files\Internet Explorer\IEXPLORE.EXE”,”",”C:\Documents and Settings\Administrator”,”open”
Browser(“Google”).Page(“Google”).Sync
Browser(“Google”).Navigate “http://www.jjperfumes.com/”
Wait (8)
Browser_Name = Browser(“Google”).GetROProperty(“title”)
If  Browser_Name=”JJ Perfumes-Discount perfume cheap brand name perfumes, fragrance & cologne online”  Then
Launch_App=”Jjperumes.com Browser Launched Sucessfully”
Msgbox Launch_App
Else
Launch_App=”Jjperumes.com Browser Not Launched”
Msgbox Launch_App
End If
End Function
**********************************************************

v) Login Operation In Flight Reservation Application

Function Login (Agent, Password)
SystemUtil.Run “C:\Program Files\HP\QuickTest Professional\samples\flight\app\flight4a.exe”,”",”C:\Program Files\HP\QuickTest Professional\samples\flight\app\”,”open”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set Agent
Dialog(“Login”).WinEdit(“Password:”).Set Password
wait 2
Dialog(“Login”).WinButton(“OK”).Click
If Window(“Flight Reservation”).Exist(12) Then
Window(“Flight Reservation”).Close
Login=”Login Operation Sucessful”
Msgbox Login
Else
SystemUtil.CloseDescendentProcesses
‘If Dialog(“Login”).Dialog(“Flight Reservations”).Exist(2) Then
‘Dialog(“Login”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
‘Dialog(“Login”).WinButton(“Cancel”).Click
‘End if
Login=”Login Failed”
Msgbox Login
End if
End Function
———————————

vi) Open Order In Flight Reservation Application

Function Open_Order(Order_Number)
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set Order_Number
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrdNum = Window(“Flight Reservation”).WinEdit(“Order No:”).GetVisibleText()
OrdNum=CInt(OrdNum)
If  OrdNum=Order_Number Then
Open_Order= Order_Number& ” Opened sucessfully”
Msgbox Open_Order
Else
Open_Order= Order_Number& ” Not Opened”
Msgbox Open_Order
End If
End Function
——————————————

vii) Update Order In Flight Reservation Application

Function Update_Order(Tickets)
Window(“Flight Reservation”).Activate
Window(“Flight Reservation”).WinButton(“Button”).Click
Window(“Flight Reservation”).Dialog(“Open Order”).WinCheckBox(“Order No.”).Set “ON”
Window(“Flight Reservation”).Dialog(“Open Order”).WinEdit(“Edit”).Set “2″
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Window(“Flight Reservation”).WinEdit(“Tickets:”).Set Tickets
Window(“Flight Reservation”).WinButton(“Update Order”).Click
Wait (10)
Message = Window(“Flight Reservation”).ActiveX(“Threed Panel Control”).GetROProperty(“text”)
If Message=”Update Done…” Then
Update_Order=”Order Updated Sucessfully”
Msgbox Update_Order
Else
Update_Order=”Order Not Updated”
Msgbox Update_Order
End If
End Function
—————————————–

viii) ‘Write Function to Count how many Browsers opened on desktop and close them all

Function Close_Browsers()
Dim oBrowser, Browsers, TotBrowsers, i
Set oBrowser=Description.Create
oBrowser(“micclass”).Value=”Browser”
Set Browsers=Desktop.ChildObjects(oBrowser)
TotBrowsers=Browsers.Count
Msgbox TotBrowsers
For i= 0 to TotBrowsers-1 Step 1
Browsers(i).close
Next

End Function

—————————

ix) ‘Write Function to Count how many Buttons available in FR Window

Function Count_Buttons()
Dim oButton, Buttons, TotButtons, i
Set oButton=Description.Create
oButton(“Class Name”).Value=”WinButton”
Set Buttons=Window(“text:=Flight Reservation”).ChildObjects(oButton)
TotButtons=Buttons.Count
Msgbox TotButtons
End Function
Call Count_Buttons()
—————————–

x) ‘Write Function to Count how many Objects available in FR Window by specified Test Object class

Function Count_Objects(Object)
Dim obj, Objects, TotObjects, i
Set obj=Description.Create
obj(“Class Name”).Value=Object
Set Objects=Window(“text:=Flight Reservation”).ChildObjects(obj)
TotObjects=Objects.Count
Msgbox TotObjects
End Function
Call Count_Objects(“WinRadioButton”)
Call Count_Objects(“WinButton”)
Call Count_Objects(“WinEdit”)
Call Count_Objects(“WinComboBox”)
——————————–

xi) ‘Write function to capture all button names one by one from Login Dialog Box

Function Capture_Buttons()
Dim oButton, Buttons, TotButtons, i, myButton
Set oButton=Description.Create
oButton(“Class Name”).Value=”WinButton”
Set  Buttons=Dialog(“text:=Login”).ChildObjects(oButton)
TotButtons=Buttons.Count
For i= 0 to TotButtons-1
myButton=Buttons(i).GetRoProperty(“text”)
Msgbox myButton
Next
End Function
Call Capture_Buttons()
——————————————
xii) ‘Write function to Count Howmany Links available in Google Homepage
Function Count_Links()
Dim oLink, Links, TotLinks, i
Set oLink=Description.Create
oLink(“micclass”).Value=”Link”
Set  Links=Browser(“title:=Google”).Page(“title:=Google”).ChildObjects(oLink)
TotLinks=Links.Count
Msgbox TotLinks
End Function
Call Count_Links()
Regular Expressions in QTP

What is Regular Expression?

It is a way of representing data using symbols. They are often used within matching, searching or replacing algorithms.

Regular Expressions in QTP:

Regular expressions can be used in QTP for identifying objects and text strings with varying values.

Where we use: 

o Defining the property values of an object in Descriptive programming for  handling dynamic objects
o For parameterizing a step
o creating checkpoints with varying values
Using Regular Expressions in QTP:

We can define a regular expression for a constant value, a Data Table parameter value, an Environment parameter value, or a property value in Descriptive programming.

We can define a regular expression in standard checkpoint to verify the property values of an object; we can set the expected value of an object's property as a regular expression so that an object with a varying value can be verified.

We can define the text string as a regular expression, when creating a text checkpoint to check that a varying text string is displayed on our application,
For XML checkpoints we can set attribute or element values as regular expressions.

Ways of Regular Expressions:

a) Backslash Character:

 A backslash (\) can serve two purposes. It can be used in conjunction with a special character to indicate that the next character be treated as a literal character.
Alternatively, if the backslash (\) is used in conjunction with some characters that would otherwise be treated as literal characters, such as the letters n, t, w, or d, the combination indicates a special character.

b) Matching Any Single Character:

A period (.) instructs QTP to search for any single character (except for \n).
Ex:
welcome.
Matches welcomes, welcomed, or welcome followed by a space or any other single character.
c) Matching Any Single Character in a List:

Square brackets instruct QTP to search for any single character within a list of characters.
Ex:
To search for the date 1867, 1868, or 1869, enter:

186[789]
d) Matching Any Single Character Not in a List:

 When a caret (^) is the first character inside square brackets, it instructs QTP to match any character in the list except for the ones specified in the string.
Example:
[^ab]
Matches any character except a or b.
e) Matching Any Single Character within a Range:

 To match a single character within a range, we can use square brackets ([ ]) with the hyphen (-) character.
Example:
For matching any year in the 2010s, enter:

201[0-9]
f) Matching Zero or More Specific Characters:

 An asterisk (*) instructs QTP to match zero or more occurrences of the preceding character.
For example:

ca*r

Matches car, caaaaaar, and cr
g) Matching One or More Specific Characters:

 A plus sign (+) instructs QTP to match one or more occurrences of the preceding character.
For example:
ca+r
Matches car and caaaaaar, but not cr.

h) Matching Zero or One Specific Character:

A question mark (?) instructs QTP to match zero or one occurrences of the preceding character.
For example:
ca?r
Matches car and cr, but nothing else.
i) Grouping Regular Expressions:

 Parentheses (()) instruct QTP to treat the contained sequence as a unit, just as in mathematics and programming languages. Using groups is especially useful for delimiting the argument(s) to an alternation operator ( | ) or a repetition operator ( * , + , ? , { } ).
j)  Matching One of Several Regular Expressions:

 A vertical line (|) instructs QTP to match one of a choice of expressions.
k)  Matching the Beginning of a Line:

 A caret (^) instructs QTP to match the expression only at the start of a line, or after a newline character.

l)  Matching the End of a Line:

A dollar sign ($) instructs QTP to match the expression only at the end of a line, or before a newline character.
m)  Matching Any AlphaNumeric Character Including the Underscore:

 \w instructs QTP to match any alphanumeric character and the underscore (A-Z, a-z, 0-9, _).
n)  Matching Any Non-AlphaNumeric Character:

 \W instructs QTP to match any character other than alphanumeric characters and underscores.
o) Combining Regular Expression Operators:

We can combine regular expression operators in a single expression to achieve the exact search criteria we need.
For example,
start.*
Matches start, started, starting, starter, and so forth.
we can use a combination of brackets and an asterisk to limit the search to a combination of non-numeric characters.
For example:
[a-zA-Z]*
To match any number between 0 and 1200, we need to match numbers with 1 digit, 2 digits, 3 digits, or 4 digits between 1000-1200.
The regular expression below matches any number between 0 and 1200.
([0-9]?[0-9]?[0-9]|1[01][0-9][0-9]|1200)
RegExp object

VB Script is providing RegExp object for defining Regular expressions, It provides simple support for defining regular expressions.
Regular Expression Object Properties and Methods:

Properties:

a) Global Property

b) IgnoreCase Property

c) Pattern Property

Methods:

a) Execute Method

b) Replace Method

c) Test Method
Regular Expressions Examples:

1) Match File Names in a Directory against Regular Expression

Set objFS = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
strCurrentDirectory = objShell.CurrentDirectory

Set objFolder = objFS.GetFolder(strCurrentDirectory)
Set colFiles = objFolder.Files

Set objRE = New RegExp
objRE.Global     = True
objRE.IgnoreCase = False
objRE.Pattern    = WScript.Arguments(0)

For Each objFile In colFiles
   bMatch = objRE.Test(objFile.Name)
   If bMatch Then
      WScript.Echo objFile.Name
   End If
Next

2) Match Content in a File against a Regular Expression
strFileName = "E:\gcreddy.txt"
Set objFS = CreateObject("Scripting.FileSystemObject")

Set objTS = objFS.OpenTextFile(strFileName)
strFileContents = objTS.ReadAll
WScript.Echo "Searching Within: "
WScript.Echo strFileContents
objTS.Close

Set objRE = New RegExp
objRE.Global     = True
objRE.IgnoreCase = False
objRE.Pattern    = WScript.Arguments(0)

Set colMatches = objRE.Execute(strFileContents)
WScript.Echo vbNewLine & "Resulting Matches:"
For Each objMatch In colMatches
   WScript.Echo "At position " & objMatch.FirstIndex & " matched " & objMatch.Value
Next

jects


VB Script Objects 
a) FileSystemObject


Scripting allows us to process drives, folders, and files using the FileSystemObject (FSO) object model.

Creating FileSystemObject:

Set Variable=CreateObject("Scripting.FileSystemObject")
Example:

Dim objFso
Set objFso=CreateObject("Scripting.FileSystemObject")
objFso.CteateTextFile("D:\gcreddy.txt")

b) Dictionary

Creating Dictionary Object:

Set Variable=CreateObject("Scripting.Dictionary")
Example:

c) Excel Application


Creating Excel Object:

Set Variable=CreateObject("Excel.Application")
Example:

d) Word Application


Creating Word Object:

Set Variable=CreateObject("Word.Application")
Example:

e) Shell


Creating Shell Object:

Set Variable= WScript.CreateObject("Wscript.Shell")
Example:

f) Network


Creating Network Object:

Set Variable= WScript.CreateObject("WScript.Network")
Example:

g) PowerPoint


Creating PowerPointObject:

Set Variable=CreateObject("PowerPoint.Application")
Example:

h) ADODB Connection


The ADO Connection Object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

Creating Database Connection Object:

Set Variable=CreateObject("ADODB.Connection")
Example:

i) ADODB RecordSet

The ADO Recordset object is used to hold a set of records from a database table. A Recordset object consist of records and columns (fields).

Creating Database RecordSet Object:

Set Variable=CreateObject("ADODB.RecordSet")
Example:

j) ADODB Command

The ADO Command object is used to execute a single query against a database. The query can perform actions like creating, adding, retrieving, deleting or updating records.

Creating Database Command Object:

Set Variable=CreateObject("ADODB.Command")
Example:

k) Error 


Creating Error Object:

l) RegExp 


 Creating RegExp Object:

Set objReg=CreateObject("vbscript.regexp")

m) Internet Explorer




n) Outlook Express
 
a) Dictionary Object

 Dictionary Object that stores data key, item pairs.

A Dictionary object is the equivalent of a PERL associative array/Hash Variable. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.



Creating a Dictionary Object:
Set objDictionary = CreateObject("Scripting.Dictionary") 
Dictionary Objects Methods: 


Add Method 

Adds a key and item pair to a Dictionary object

Exists Method

Returns true if a specified key exists in the Dictionary object, false if it does not.

Items Method

Returns an array containing all the items in a Dictionary object.

Keys Method

Returns an array containing all existing keys in a Dictionary object.

Remove Method

Removes a key, item pair from a Dictionary object.

RemoveAll Method

The RemoveAll method removes all key, item pairs from a Dictionary object.
 
Example:


Dim cities
Set cities = CreateObject("Scripting.Dictionary")
cities.Add "h", "Hyderabad"
cities.Add "b", "Bangalore"
cities.Add "c", "Chennai"



Dictionary Objects Properties:
Count Property

Returns the number of items in a collection or Dictionary object. Read-only.

CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary object.

Key Property

Sets a key in a Dictionary object.

Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.
 

Examples:


1) Add Elements to a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

2) Delete All Elements from a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")



objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
colKeys = objDictionary.Keys

Wscript.Echo "First run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next

objDictionary.RemoveAll
colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next

3) Delete One Element from a Dictionary

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"  
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

colKeys = objDictionary.Keys

Wscript.Echo "First run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next

objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys

Wscript.Echo VbCrLf & "Second run: "
For Each strKey in colKeys
    Wscript.Echo strKey
Next

4) List the Number of Items in a Dictionary


Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"   
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"
Wscript.Echo objDictionary.Count


5) Verify the Existence of a Dictionary Key

Set objDictionary = CreateObject("Scripting.Dictionary")

objDictionary.Add "Printer 1", "Printing"  
objDictionary.Add "Printer 2", "Offline"
objDictionary.Add "Printer 3", "Printing"

If objDictionary.Exists("Printer 4") Then
    Wscript.Echo "Printer 4 is in the Dictionary."
Else
    Wscript.Echo "Printer 4 is not in the Dictionary."
End If

VBScript Coding Conventions


Coding conventions are suggestions are designed to help us write code using VB Script.
Coding conventions can include the following: 

Naming conventions for objects, variables, and procedures
Commenting conventions
Text formatting and indenting guidelines 

The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that we and others can easily read and understand the code.

Using good coding conventions results in clear, precise, and readable source code that is consistent with other language conventions and is intuitive.

Variable Naming Conventions
To enhance readability and consistency, we have to use the following prefixes with descriptive names for variables in our VBScript code.

Subtype         Prefix             Example
----------------------------------------------
Boolean         bln                  blnFound
-----------------------------------------------
Byte              byt                  bytRasterData
-----------------------------------------------------
Date (Time)   dtm                 dtmStart
----------------------------------------------------
Double          dbl                  dblTolerance
-----------------------------------------------------
Error             err                   errOrderNum
----------------------------------------------------- 
Integer          int                   IntQuantity
-----------------------------------------------------
Long             lng                   lngDistance
----------------------------------------------------- 
Object           obj                   objCurrent
-----------------------------------------------------
Single           sng                  sngAverage
-----------------------------------------------------
String           str                    strFirstName
-----------------------------------------------------

Object Naming Conventions:
The following table lists recommended conventions for objects you may encounter while programming VBScript.

Object type           Prefix        Example
---------------------------------------------------
3D Panel               pnl            pnlGroup
---------------------------------------------------
Animated button    ani            aniMailBox
---------------------------------------------------
Check box             chk            chkReadOnly
---------------------------------------------------
Combo box            cbo            cboEnglish
---------------------------------------------------
Command button   cmd            cmdExit
---------------------------------------------------
Common dialog     dlg             dlgFileOpen
---------------------------------------------------
Frame                 fra              fraLanguage
---------------------------------------------------

Image                 img            imgIcon
---------------------------------------------------
Label                   lbl             lblHelpMessage
---------------------------------------------------
Line                    lin              linVertical
---------------------------------------------------
List Box               lst             lstPolicyCodes
---------------------------------------------------
Spin                    spn            spnPages
---------------------------------------------------
Text box              txt             txtLastName
---------------------------------------------------

Slider                  sld             sldScale
---------------------------------------------------

Code Commenting Conventions

All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation.

Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a procedure, especially through reference arguments, should also be described at the beginning of each procedure.

Procedure header comments should include the following section headings. For examples, see the "Formatting Your Code" section that follows.

Section Heading     Comment Contents

Purpose:   What the procedure does (not how).

Assumptions:   List of any external variable, control, or otherelement             whose state affects this procedure.

Effects:    List of the procedure's effect on each external variable, control, or other element.

Inputs
:  Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.

Return Values:    Explanation of the value returned.

Remember the following points:

Every important variable declaration should include an inline comment  describing the use of the variable being declared.

Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details.

At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode describing the algorithm can be helpful.

Formatting the Code
Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few suggestions:

•    Indent standard nested blocks four spaces.

•    Indent the overview comments of a procedure one space.

•    Indent the highest level statements that follow the overview comments four spaces, with each nested block indented an additional four spaces.

The following code adheres to VBScript coding conventions.
'*********************************************************
' Purpose: Locates the first occurrence of a specified user
'          in the UserList array.
' Inputs: strUserList(): the list of users to be searched.
'         strTargetUser: the name of the user to search for.
' Returns: The index of the first occurrence of the strTargetUser
'          in the strUserList array.
'          If the target user is not found, return -1.
'*********************************************************
Function intFindUser (strUserList(), strTargetUser)
    Dim i   ' Loop counter.
    Dim blnFound   ' Target found flag
    intFindUser = -1
    i = 0   ' Initialize loop counter
    Do While i <= Ubound(strUserList) and Not blnFound
      If strUserList(i) = strTargetUser Then
         blnFound = True   ' Set flag to True
         intFindUser = i   ' Set return value to loop count
      End If
      i = i + 1   ' Increment loop counter
    Loop
End Function

 VBScript Classes
 Creating Classes

Classes aren't a new concept in scripting. JavaScript, JScript, and other scripting languages have supported classes or similar elements for years. However, VBScript 5.0 is the first version of VBScript to support classes.

To use classes in your VBScript code, you first need to obtain VBScript 5.0 by downloading the appropriate self-executable file from the Microsoft Developer Network (MSDN) Web site (http://msdn.microsoft.com/scripting) or by installing Microsoft Internet Explorer (IE) 5.0. Then you need to understand what a VBScript class is and learn how to declare, define, initialize, and instantiate a class.

VBScript Classes 

VBScript 5.0 supports two types of objects: COM objects and Class objects (typically referred to as simply classes). VBScript COM objects have basic subtypes, such as an Integer or String. VBScript classes have an abstract subtype that encapsulates data and the functions to work with that data. You can think of a VBScript class as having a souped-up subtype that provides you with more computing power and flexibility. (Other differences exist between these two types of objects. For more information, see the Web-exclusive sidebar "How VBScript Classes and COM Objects Differ" on the Win32 Scripting Journal Web site at http://www.winntmag.com/ newsletter/scripting.

You can use classes to describe complex data structures. For example, if your application tracks customers and orders, you can define two classes for them, each with a unique set of internal data (typically called properties) and functions (typically called methods). You can then manage customers and orders as if they were native VBScript subtypes. More important, because you assign a class its properties and methods (i.e., its programming interface), you have an object-oriented tool to improve VBScript applications.

Declaring a Class 

You use the Class statement to declare a class. This statement's syntax is:

Class name
' Properties and methods go here.
End Class
where name is the name you give that class. You declare the properties and methods for your class between the Class and End Class clauses.

For example, suppose you want to create the VBScript class FileList, which Listing 1 contains. This class manages those files in a folder that meet a filename specification that you provide. You create this class by first specifying the keyword Class followed by the class' name Class FileList. Next, you declare the class' properties and methods. FileList has two properties (FileSpec and FolderPath) and one method (Search).

Declaring the FileSpec Property 

The FileSpec property holds the filename specification. For example, the filename specification might be C:\*.*. You want users to be able to freely read and write values to this property, so you declare FileSpec as an external, or public, variable with the Public statement

Public FileSpec

You can use a public variable in any script, not just the script in which you created the variable. However, if you use a public variable, you have no control over the value that users assign to the variable and no control over the value that the variable returns. Thus, you can't use public variables to hold values that you need to validate.

Declaring the FolderPath Property

The FolderPath property holds the full path to the folder containing the files. After a user sets a folder path, you need to validate that the folder exists, which means you can't use a public variable. Instead, you need to store the folder path in an internal, or private, variable and use two public property procedures to read and write to that variable. (Public property procedures are wrappers that hide the code that gets and sets the values of private variables.)

Prefixing a private variable with the m_ string is a common scripting convention. For example, the private variable for the FolderPath property is m_folderPath. To declare m_folderPath, you use the Private statement

Private m_folderPath

Procedures and variables that have the Private qualifier aren't visible outside the class. In addition, private variables apply only to the script in which you created them.

After you declare m_folderPath, you need to declare the two public property procedures that you'll use to read and write to that variable. The first procedure to declare is the Property Get procedure, which returns the values of properties. The second procedure is the Property Let procedure, which assigns values to properties.

To declare the Property Get procedure, you use the Property Get statement

Public Property Get FolderPath
    FolderPath = m_folderPath
End Property
where FolderPath is the name of that procedure. By including the Public statement with the Property Get statement, you're making the value that the FolderPath procedure returns available for public reading. Thus, by assigning FolderPath to m_folderPath, you make the value of m_folderPath available for public reading.
VBScript Syntax Rules and Guidelines

1) Case-sensitivity:

By default, VBScript is not case sensitive and does not differentiate between upper-case and lower-case spelling of words, for example, in variables, object and method names, or constants.

For example, the two statements below are identical in VBScript:

Browser("Mercury").Page("Find a Flight:").WebList("toDay").Select "31"
browser("mercury").page("find a flight:").weblist("today").select "31"

2) Text strings:

When we enter a value as a text string, we must add quotation marks before and after the string. For example, in the above segment of script, the names of the Web site, Web page, and edit box are all text strings surrounded by quotation marks.

Note that the value 31 is also surrounded by quotation marks, because it is a text string that represents a number and not a numeric value.

In the following example, only the property name (first argument) is a text string and is in quotation marks. The second argument (the value of the property) is a variable and therefore does not have quotation marks. The third argument (specifying the timeout) is a numeric value, which also does not need quotation marks.

Browser("Mercury").Page("Find a Flight:").WaitProperty("items count", Total_Items, 2000)

3) Variables:

We can specify variables to store strings, integers, arrays and objects. Using variables helps to make our script more readable and flexible
 VB Script General Examples
1) Write a program for finding out whether the given year is a leap year or not?

Dim xyear
xyear=inputbox ("Enter Year")
If xyear mod 4=0 Then
msgbox "This is a Leap year"
Else
msgbox "This is NOT"
End If

2) Write a program for finding out whether the given number is, Even number or Odd number?

Dim num
num=inputbox ("Enter a number")
If num mod 2=0 Then
msgbox "This is a Even Number"
Else
msgbox "This is a Odd Number"
End If

3) Read two numbers and display the sum?

Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
msgbox ("Sum is " &sum)

4) Read P,T,R values and Calculate the Simple Interest?

Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)

5) Read Four digit number, calculate & display the sum of the number or display Error message if the number is not a four digit number?

Dim num, sum
num=inputbox ("Enter a Four digit number")
If Len(num) = 4 Then
sum=0
sum=sum+num mod 10
num=num/10
num= left (num, 3)
sum=sum+num mod 10
num=num/10
num= left (num, 2)
sum=sum+num mod 10
num=num/10
num= left (num, 1)
sum=sum+num mod 10
msgbox ("Sum is " &sum)
else
msgbox "Number, you entered is not a 4 digit number"
End If

6) Read any Four-digit number and display the number in reverse order?

Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
rev=rev*10 + num mod 10
num=num/10
num= left(num,3)
rev=rev*10 + num mod 10
num=num/10
num= left(num,2)
rev=rev*10 + num mod 10
num=num/10
num= left(num,1)
rev=rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If

7) Read 4 subjects marks; calculate the Total marks and grade?

a) If average marks Greater than or equal to 75, grade is Distinction
b) If average marks Greater than or equal to 60 and less than 75 , then grade is First
c) If average marks Greater than or equal to 50 and less than 60 , then grade is Second
d) If average marks Greater than or equal to 40 and less than 50 , then grade is Third
e) Minimum marks 35 for any subject, otherwise 'no grade fail')

Dim e,m,p,c, tot
e=inputbox ("Enter english Marks")
m=inputbox ("Enter maths Marks")
p=inputbox ("Enter physics Marks")
c=inputbox ("Enter chemistry Marks")
tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)
msgbox tot
If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then
msgbox "Grade is Distinction"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then
msgbox "Grade is First"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=200 and tot<240 Then
msgbox "Grade is Second"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=160 and tot<200 Then
msgbox "Grade is Third"
else
msgbox "No Grade, Fail"
End If
End If
End If
End If

8) Display Odd numbers up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num
Next

9) Display Even numbers up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next

10) display natural numbers up to n and write in a text file?

Dim num, n, fso, myfile
n= inputbox ("Enter any Value")
num=1
For num= 1 to n step 1
Set fso= createobject ("scripting.filesystemobject")
set myfile=fso.opentextfile ("E:\gcreddy.txt", 8, true)
myfile.writeline num
myfile.close
Next

11) Display Natural numbers in reverse order up to n?

Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next

12) Display Natural numbers sum up to n? (Using For...Next Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum

13) Display Natural numbers sum up to n? (using While...Wend Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
While num <=cdbl (n)
sum= sum+num
num=num+1
Wend
msgbox sum

14) Display Natural numbers sum up to n? (Using Do...Until...Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
sum=0
num=1
Do
sum= sum+num
num=num+1
Loop Until num =cdbl (n+1)
msgbox sum

15) Write a Function for Natural Numbers sum up to n?

Function NNumCou (n)
Dim num, sum
sum=0
For num= 1 to n step 1
sum= sum+num
Next
msgbox sum
End Function

16) Verify weather the entered 10 digit value is a numeric value or not?

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then

msgbox "It is a Numeric Value"
else
Msgbox "It is NOT Numeric"
End If

17) Verify weather the entered value is a 10 digit value or not and Numeric value or not? (Using multiple if conditions)

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))

If len (num) =10 Then

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
End If
End If

If len (num) <> 10 Then
Msgbox "It is NOT valid Number "
End If
18) Generate interest for 1 to 5 years (for 1 year -7%,  2 years -8%, 3 years-9%, 4 years-10%,  5 years -11%)
Dim amount, duration, intr
amount=inputbox("enter amount")
If amount<10000 Then
msgbox "low amount"
else
For duration=1 to 5
If duration=1 Then
intr=amount*7/100
msgbox "1 year intrest is: " &intr

else if duration=2 Then
intr=amount*8/100
msgbox "2 years intrest is: " &intr

else if duration=3 Then
intr=amount*9/100
msgbox "3 years intrest is: "&intr

else if duration=4 Then
intr=amount*10/100
msgbox "4 years intrest is: "&intr

else if duration=5 Then
intr=amount*11/100
msgbox "5 years intrest is: "&intr
else
msgbox "invalid data"
End If
End If
End If
End If
End If
Next
End If
4) Parentheses:

 To achieve the desired result and to avoid errors, it is important that we use parentheses () correctly in our statements.

5) Indentation:

We can indent or outdent our script to reflect the logical structure and nesting of the statements.

6) Comments:

We can add comments to our statements using an apostrophe ('), either at the beginning of a separate line, or at the end of a statement. It is recommended that we add comments wherever possible, to make our scripts easier to understand and maintain.


7) Spaces:

We can add extra blank spaces to our script to improve clarity. These spaces are ignored by VBScript.
VBScript General Examples


1) Read a value and find size of the value

Dim val: val=Inputbox("Enter value for val: ")
val_length =Len(val)
msgbox "Size of "&val&" is "&val_length


2) Read a value and find whether the value is numeric or not?

Dim val: val=Inputbox("Enter value for val: ")
val_type =IsNumeric(val)
If val_type = true Then
    msgbox "val is Numeric"
else
    msgbox "val is not Numeric"
End If

3)'Read a value and find whether the value is Date type data or not?

Dim val: val=Inputbox("Enter value for val: ")
val_type =IsDate(val)
If val_type = true Then
    msgbox "val is Date type data"
else
    msgbox "val is not date type"
End If


4)Read a value and Verify whether the value is 10-digit number or not and started with 9 0r 8.

'Then Display it is a valid mobile number

Dim val,val_Length, val_Numeric, val_Start
val=Inputbox("Enter value for val: ")
val_Length= Len(val)
val_Numeric=IsNumeric(val)
val_Start=Left(val,1)
If val_Length=10 and val_Numeric and val_Start=9 or val_Start=8 Then
    msgbox val&"  is a valid mobile number "
Else
    msgbox val&"  is not a valid mobile number "
End If

5) 'Read a mobile number and verify the series

'if it starts with 92478 or 92471 then display it is TataIndicom number
'if it starts with 98490 or 98480 then display it is Airtel number

Dim val, val_Length,val_Numeric,val_Series,val_Start
val=Inputbox("Enter value for val: ")
val_Length= Len(val)
val_Numeric=IsNumeric(val)
val_Start=Left(val,1)
val_Series=Left(val,5)
If val_Numeric=true Then

If val_Length=10 and val_Start=9  Then

    If val_Series = 92478 or val_Series=92471 Then
        msgbox "It is TataIndicom Number"
    ElseIf val_Series=98490 or val_Series = 98480 then
        msgbox "It is Airtel Number"
    End If

Else
    msgbox val&"  is not a valid mobile number "
End If
Else
    msgbox val& " is Invalid data"
End If

6) Read a Value and Verify weather the value is started with Alfa bytes or not? (First letter should be Alfa byte)

Dim val, val_Asc

val=Inputbox("enter a value")
val_Asc=Asc(val)
Msgbox val_Asc
If val_Asc>=65 and val_Asc<=90 or val_Asc>=97 and val_Asc<=122Then
    msgbox val&" is an Alphabet"
Else
    msgbox val&" is not an Alphabet"
End If

7) Read a value and Verify weather the value is Alfa bytes are not?
Dim str, valAsc, flag,i
Dim strlen, counter,valsingle
counter=0

str=Inputbox("enter a string value")
strlen= Len(str)
For i=1 to strlen step 1
        valsingle=Mid(str,i,1)
        valAsc=Asc(valsingle)

        If valAsc>=65 and valAsc<=90 or valAsc>=97 and valAsc<=122Then
                flag=1
                counter=counter+1
        Else
                flag=0
        End If
Next

msgbox "No.of characters  " &counter

If counter=strlen and flag=1Then
    msgbox str&" is an Alphabetic value"
Else
    msgbox str&" is not a
 VB Script Glossary of Terms
ActiveX control
An object that you place on a form to enable or enhance a user's interaction with an application. ActiveX controls have events and can be incorporated into other controls. The controls have an .ocx file name extension.


ActiveX object
An object that is exposed to other applications or programming tools through Automation interfaces.

Argument
A constant, variable, or expression passed to a procedure.

Array
A set of sequentially indexed elements having the same type of data. Each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements.

ASCII Character Set
American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0–127) in the ANSI character set.

Automation object
An object that is exposed to other applications or programming tools through Automation interfaces.

Bitwise comparison
A bit-by-bit comparison of identically positioned bits in two numeric expressions.

Boolean expression
An expression that evaluates to either True or False.

By reference
A way of passing the address, rather than the value, of an argument to a procedure. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed.

By value
A way of passing the value, rather than the address, of an argument to a procedure. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed.

character code
A number that represents a particular character in a set, such as the ASCII character set.

Class
The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior.

Class module
A module containing the definition of a class (its property and method definitions).

Collection
An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary.

Comment
Text added to code by a programmer that explains how the code works. In Visual Basic Scripting Edition, a comment line generally starts with an apostrophe ('), or you can use the keyword Rem followed by a space.

Comparison operator
A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (=).

Is is also a comparison operator, but it is used exclusively for determining if one object reference is the same as another.

Constant
A named item that retains a constant value throughout the execution of a program. Constants can be used anywhere in your code in place of actual values. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. For example:
Data ranges
Each Variant subtype has a specific range of allowed values:
Subtype Range
Byte 0 to 255.
Boolean True or False.
Integer -32,768 to 32,767.
Long -2,147,483,648 to 2,147,483,647.
Single -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date January 1, 100 to December 31, 9999, inclusive.
Object Any Object reference.
String Variable-length strings may range in length from 0 to approximately 2 billion characters.

Date expression
Any expression that can be interpreted as a date. This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999.
Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899.

Date literal
Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format. For example, #12/31/99# is the date literal that represents December 31, 1999, where English-U.S. is the locale setting for your application.
In VBScript, the only recognized format is US-ENGLISH, regardless of the actual locale of the user. That is, the interpreted format is mm/dd/yyyy.

Date separators
Characters used to separate the day, month, and year when date values are formatted.

Empty
A value that indicates that no beginning value has been assigned to a variable. Empty variables are 0 in a numeric context, or zero-length in a string context.

Error number
A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the Err object. When combined with the Name property of the Err object, this number represents a particular error message.

Expression
A combination of keywords, operators, variables, and constants that yield a string, number, or object. An expression can perform a calculation, manipulate characters, or test data.
Intrinsic constant
A constant provided by an application. Because you can't disable intrinsic constants, you can't create a user-defined constant with the same name.

Keyword
A word or symbol recognized as part of the VBScript language; for example, a statement, function name, or operator.

Locale
The set of information that corresponds to a given language and country. A locale affects the language of predefined programming terms and locale-specific settings. There are two contexts where locale information is important:
• The code locale affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.
• The system locale affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system.
Nothing
The special value that indicates that an object variable is no longer associated with any actual object.

Null
A value indicating that a variable contains no valid data. Null is the result of:
• An explicit assignment of Null to a variable.
• Any operation between expressions that contain Null.

Numeric expression
Any expression that can be evaluated as a number. Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number.

Object type
A type of object exposed by an application, for example, Application, File, Range, and Sheet. Refer to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on) for a complete listing of available objects.

pi
Pi is a mathematical constant equal to approximately 3.1415926535897932.

Private
Variables that are visible only to the script in which they are declared.

Procedure
A named sequence of statements executed as a unit. For example, Function and Sub are types of procedures.

Procedure level
Describes statements located within a Function or Sub procedure. Declarations are usually listed first, followed by assignments and other executable code. For example:

Sub MySub() ' This statement declares a sub procedure block.
Dim A ' This statement starts the procedure block.
A = "My variable" ' Procedure-level code.
Debug.Print A ' Procedure-level code.
End Sub ' This statement ends a sub procedure block.
Note that script-level code resides outside any procedure blocks.

Property
A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.

Public
Variables declared using the Public Statement are visible to all procedures in all modules in all applications.

Run time
The time when code is running. During run time, you can't edit the code.

Run-time error
An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation.

Scope
Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public is visible to all procedures in all modules. Variables declared in procedures are visible only within the procedure and lose their value between calls.

SCODE
A long integer value that is used to pass detailed information to the caller of an interface member or API function. The status codes for OLE interfaces and APIs are defined in FACILITY_ITF.

Script level
Any code outside a procedure is referred to as script-level code.

Seed
An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.

String comparison
A comparison of two sequences of characters. Unless specified in the function making the comparison, all string comparisons are binary. In English, binary comparisons are case-sensitive; text comparisons are not.

String expression
Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, or a string variable.

Type library
A file or component within another file that contains standard descriptions of exposed objects, properties, and methods.

Variable
A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its level of scope.
Variable names:
• Must begin with an alphabetic character.
• Can't contain an embedded period or type-declaration character.
• Must be unique within the same scope.
• Must be no longer than 255 characters.