Beruflich Dokumente
Kultur Dokumente
VB Script
For
QTP
VB Script For QTP 2
VB Script Comments
Comments
Purpose of comments:
Syntax
Rem comment (After the Rem keyword, a space is required before comment.)
Or
Apostrophe (') symbol before the comment
o Select block of statement and use short cut key Ctrl + M (for comment)
o Select comment block and use short cut key Ctrl + Shift + M (for uncomment)
VB Script For QTP 3
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
Example:
Cost=Tickets*Price
c) Passing parameters
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
Example:
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.
Variable names follow the standard rules for naming anything in VBScript. A
variable name:
Scope of Variables
When we declare a variable within a procedure, only code within that procedure
VB Script For QTP 5
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
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
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)
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.
VB Script For QTP 7
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)
There is no limit to the number of times we can resize a dynamic array, although
if we make an array smaller, we lose the data in the elimina
VB Script For QTP 8
VBScript has only one data type called a Variant. A Variant is a special kind of
data type that can contain different kinds of information, depending on how it is
used. Because Variant is the only data type in VBScript, it is also the data type
returned by all functions in VBScript.
Variant Subtypes
Beyond the simple numeric or string classifications, a Variant can make further
distinctions about the specific nature of numeric information. For example, we
can have numeric information that represents a date or a time. When used with
other date or time data, the result is always expressed as a date or a time. We
can also have a rich variety of numeric information ranging in size from Boolean
values to huge floating-point numbers. These different categories of information
that can be contained in a Variant are called subtypes. Most of the time, we can
just put the kind of data we want in a Variant, and the Variant behaves in a way
that is most appropriate for the data it contains.
The following table shows subtypes of data that a Variant can contain.
VB Script For QTP 9
VB Script Operators
Operator Precedence
We can use parentheses to override the order of precedence and force some
parts of an expression to be evaluated before others.
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.
1) Arithmetic Operators:
Operator Description
1) Exponentiation Operator (^) Raises a number to the power of an exponent
4) Integer Division Operator (\) Divides two numbers and returns an integer
result.
5) Mod Operator Divides two numbers and returns only the remainder.
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
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
VB Script For QTP 11
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
Operator Description
VB Script For QTP 12
3) Concatenation Operators
Operator Description
1) Addition Operator (+)
4) Logical Operators
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 For QTP 14
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
Example:
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
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
Dim x
x= 20
If x>10 Then
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
Example:
Dim x
x= Inputbox (" Enter a value")
Else
VB Script For QTP 17
Example:
End If
End If
End If
End If
Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
VB Script For QTP 18
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
VB Script For QTP 19
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
Example:
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
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
Dim x
x= 20
If x>10 Then
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
Example:
Dim x
x= Inputbox (" Enter a value")
Else
VB Script For QTP 22
Example:
End If
End If
End If
End If
Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
VB Script For QTP 23
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
VB Script For QTP 24
1) Using Do Loops
The statements are repeated either 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
-----------
VB Script For QTP 25
-----------
Loop While condition
Example:
Dim x
x=1
Do
Msgbox "Hello G.C.Reddy"
Msgbox "Hello QTP"
x=x+1
Loop While x<5
Dim x
Do Until x=5 x=x+1
Msgbox "G.C.Reddy"
Msgbox "Hello QTP"
Loop
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"
VB Script For QTP 26
x=x+1
Loop Until x=5
2 While...Wend Statement
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
Example:
Dim x
For x= 1 to 5 step 1
Msgbox "Hello G.C.Reddy"
Next
Syntax:
Example: (1
Example: (2
MyArray = Array("one","two","three","four","five")
For Each element In MyArray
msgbox element
Next
VB Script For QTP 28
VB Script Procedures
In VBScript, there are two kinds of procedures available; the Sub procedure and
the Function procedure.
1) Sub Procedures
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 similar to a Sub procedure, but can also return a value.
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
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.
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
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
VB Script For QTP 32
'******************************************
' 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
VB Script 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.
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.
VB Script Functions
o Conversions (25)
o Dates/Times (19)
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.
VB Script For QTP 37
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
8) DateDiff Function
Returns the number of intervals between two dates.
Dim myday
mydate=#02-17-2009#
x=Datediff("d",mydate,Now)
msgbox x
VB Script For QTP 38
9) Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of
the day.
Dim mytime
mytime=Time
msgbox mytime
Dim MyCheck
MyCheck = VarType(300) ' Returns 2.
Msgbox Mycheck
MyCheck = VarType(#10/19/62#) ' Returns 7.
Msgbox Mycheck
MyCheck = VarType("VBScript") ' Returns 8.
Msgbox Mycheck
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
Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6)
Msgbox MyVar
* It Returns ‘Script’ *
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)
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 *
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
20) CreateObject
'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)
'creates and returns reference of the Word Object to an Automation object. It can
be used for performing operations on Ms-Word documents
21) Round
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
VB Script For QTP 42
) 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
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:
4) Chr Function
Returns the character associated with the specified ANSI character code.
Syntax:
VB Script For QTP 43
Chr(charcode)
' 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)
5) CLng Function
Returns an expression that has been converted to a Variant of subtype Long.
Syntax:
CLng(expression)
6) CStr Function
7) Oct Function
8) CBool Function
9) CCur Function
It is a way of representing data using symbols. They are often used within
matching, searching or replacing algorithms.
Regular expressions can be used in QTP for identifying objects and text strings
with varying values.
Where we use:
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 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.
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.
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.
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]
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.
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]
ca*r
A plus sign (+) instructs QTP to match one or more occurrences of the preceding
character.
For example:
VB Script For QTP 49
ca+r
Matches car and caaaaaar, but not cr.
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.
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 ( * , + , ? , { } ).
A caret (^) instructs QTP to match the expression only at the start of a line, or
after a newline character.
A dollar sign ($) instructs QTP to match the expression only at the end of a line,
or before a newline character.
\w instructs QTP to match any alphanumeric character and the underscore (A-Z,
a-z, 0-9, _).
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
Properties:
a) Global Property
b) IgnoreCase Property
c) Pattern Property
Methods:
a) Execute Method
b) Replace Method
c) Test Method
objRE.Pattern = WScript.Arguments(0)
VB Script Objects
a) FileSystemObject
Creating FileSystemObject:
Set Variable=CreateObject("Scripting.FileSystemObject")
Example:
Dim objFso
Set objFso=CreateObject("Scripting.FileSystemObject")
objFso.CteateTextFile("D:\gcreddy.txt")
b) Dictionary
Set Variable=CreateObject("Scripting.Dictionary")
Example:
c) Excel Application
Set Variable=CreateObject("Excel.Application")
Example:
d) Word Application
Set Variable=CreateObject("Word.Application")
Example:
e) Shell
f) Network
g) PowerPoint
Creating PowerPointObject:
Set Variable=CreateObject("PowerPoint.Application")
Example:
h) ADODB Connection
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).
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.
VB Script For QTP 54
Set Variable=CreateObject("ADODB.Command")
Example:
k) Error
l) RegExp
Set objReg=CreateObject("vbscript.regexp")
m) Internet Explorer
n) Outlook Express
a) Dictionary Object
Add Method
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
Items Method
Keys Method
Remove Method
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"
CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary
object.
Key Property
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.
VB Script For QTP 56
Examples:
a to Elements 1) AddDictionary
objDictionary.RemoveAll
colKeys = objDictionary.Keys
colKeys = objDictionary.Keys
VB Script For QTP 57
objDictionary.Remove("Printer 2")
colKeys = objDictionary.Keys
Coding conventions are suggestions are designed to help us write code using
VB Script.
Using good coding conventions results in clear, precise, and readable source
code that is consistent with other language conventions and is intuitive.
The following table lists recommended conventions for objects you may
encounter while programming VBScript.
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.
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.
•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.
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 the highest level statements that follow the overview comments four
spaces, with each nested block indented an additional four spaces.
VB Script For QTP 61
VB Script 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
VB Script For QTP 63
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).
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.
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.)
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
VB Script For QTP 64
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.
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.
3) Variables:
We can specify variables to store strings, integers, arrays and objects. Using
variables helps to make our script more readable and flexible
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.
VB Script For QTP 66
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
VB Script For QTP 67
VB Script Examples
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
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?
VB Script For QTP 68
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
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 num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num
Next
Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 2 to n step 2
msgbox num
Next
VB Script For QTP 70
Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num
Next
Do
sum= sum+num
num=num+1
Loop Until num =cdbl (n+1)
msgbox sum
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
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
VB Script For QTP 72
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
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
intr=amount*10/100
msgbox "4 years intrest is: "&intr
VB Script Examples-II
VB Script General Examples
3)'Read a value and find whether the value is Date type data or not?
End If
4)Read a value and Verify whether the value is 10-digit number or not and
started with 9 0r 8.
Else
msgbox val&" is not a valid mobile number "
End If
Else
msgbox val& " is Invalid data"
End If
VB Script For QTP 75
6) Read a Value and Verify weather the value is started with Alfa bytes or
not? (First letter should be Alfa byte)
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?
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.
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.
VB Script For QTP 78
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 (=).
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
VB Script For QTP 79
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.
VB Script For QTP 80
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
VB Script For QTP 81
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:
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.
VB Script For QTP 82
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.
VB Script For QTP 83