VBScript Tutorial for Beginners

VBScript Tutorial for Beginners, VBScript Environment, VBScript Language fundamentals, VBScript control flow, and VBScript object models.

Introduction:

• Visual Basic Scripting Edition is a lightweight language from Microsoft.

• VBScript derived from VB Programming language.

• VBScript is not a case-sensitive language.

• VBScript is a lightweight language and it has fewer formalities for writing Programs.

• VBScript is a platform-dependent language.

Usage of VBScript:

1. Client-side scripting in the Web (HTML) (Browser-IE)

2. Server-side scripting in the web (ASP) (Web Server -IIS)

3. Network Administration on Server OS (WSH)

4. System Administration on Client OS or Server OS (WSH)

5. Automated Testing (UFT/QTP)

VBScript Syllabus

1. VBScript Environment

2. Data Types and Variables

3. VBScript Constants

4. VBScript Operators

Arithmetic operators, Relational or Comparison operators, and Logical operators.

Note: Concatenation operators are Part of Arithmetic operators.

5. VBScript Conditional Statements

6. VBScript Loop Statements

7. VBScript Built-in Functions

8. VBScript User-defined Functions

9. VBScript Coding conventions

10. VBScript File System Operations

11. VBScript Excel Application Operations

12. VBScript Word Application operations

13. VBScript Database Objects

14. VBScript Dictionary Object

15. Regular Expressions

16. Error Handling in VBScript

Etc,


Data Types and Variables

Data Types:

VBScript doesn’t support Explicit declaration of Data Types.

In VBScript only the Data type is Variant, It can hold any type of data, based on usage of data VBScript internally considers Data subtypes.

Example:

Dim city

city = “Hyderabad” ‘String
——–
——–
——–
city = 100 ‘Integer
——–
——–
——–
city = 1.24 ‘Double
——–
——–
——–
city = #10/10/2015# ‘Date

We can check Data Sub types using VarType Function

Check Data Sub types:

Dim a
Msgbox VarType(a) ‘0 for Empty / Uninitialized

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

Msgbox VarType(100) ‘2 for Integer

Msgbox VarType(“abcd”) ‘8 for String

Msgbox VarType(“100”) ‘ 8 for String

Msgbox VarType(1.24) ‘ 5 for Double

Msgbox VarType(#10/10/2010#) ‘7 for Date

Set a = CreateObject(“Scripting.FileSystemObject”)
Msgbox VarType(a) ‘9 for Automation Object

Convert the Data from one sub type to another.

Why we need to convert the Data?

In Computer Programming value Assignment 2 types:

i. Initialization

Ex:

a = 100

ii. Reading
Read data using Input devices
Read data from a file
Read data from a database
Read data from Application objects
Ex:
‘Before Conversion
Dim a, b
a = InputBox(“Enter A Value”)
b = InputBox(“Enter B Value”)
Msgbox a + b

Note: If we read data then VBScript considers the data as String type data. In order to perform math-metical calculations, we need to convert the data.

> Using conversion Functions we can convert the data.

‘After Conversion
Dim a, b
a = InputBox(“Enter A Value”)
b = InputBox(“Enter B Value”)
Msgbox Cint (a) + Cint (b)

We can’t convert Alfa bytes into Integer or double type.

Ex:
Dim val, Tickets
val = InputBox(“Enter a value”)
Msgbox VarType(val) ‘8 for String
val = Cint(val)
Msgbox VarType(val)

Tickets = Window(“Flight Reservation”).WinEdit(“Tickets:”).GetROProperty(“text”)
Msgbox VarType(Tickets) ‘8 for String
Msgbox VarType(Cint(Tickets)) ‘ 2 for Integer

Variables:

1. What is a Variable?

A named memory location to store the data.

In a computer environment, there are two types of memory

i. Primary memory: RAM

ii. Secondary memory: HDD, CD-ROM, DVD, USB Drive, etc…

Variables store in Primary Memory (RAM).

2. Declaration of variables

> using either Public or Private or Dim statements, we can declare Variables.

Ex:

Dim a
Dim x, y, z
Or
Dim x
Dim y
Dim z

3. Implicit and Explicit variables.

Ex:
Dim a
a = 100 ‘Explicit
b = 200 ‘Implicit
Msgbox a + b
———————
Dim Tickets, Price, Total
Tickets = 7
Price = 100
Total = Tickets * Priee
Msgbox Total ‘0 (Incorrect output)
———–
Option Explicit
Dim Tickets, Price, Total
Tickets = 7
Price = 100
Total = Tickets * Priee
Msgbox Total ‘Error
—————————
Option Explicit, it forces declaration of all variables in a Script

4. Assigning Values to Variables

Assigning Values to Variables is two types

i. Initialization

ii. Reading

Example:
Dim num1, num2
num1 = 100 ‘Initialization
num2 = InputBox (“Enter Num2 value”) ‘ Reading
Msgbox num1 + num2

5. Purpose of Variables

Dim a, ord
‘Holding the data
a = 100
Msgbox a
‘Storing the data that returned by a Function
a = Now
Msgbox a
‘Storing the data that returned by a program
a = (10 ^ 3)*2
Msgbox a

‘storing object Reference
Set a = CreateObject(“Scripting.FileSystemObject”)

‘As parameter
For ord = 1 To 5 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 ord
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Next

6. Naming Restrictions

i. Variable names should start with Alfa bytes

Ex:
Dim abc ‘Correct
Dim a12 ‘Correct
Dim 1ab ‘Incorrect

ii. Should not contain embedded periods

Ex:
Dim abc ‘Correct
Dim ab c ‘Incorrect
Dim ab.c ‘Incorrect
Dim ab*c ‘Incorrect
Dim ab_c ‘Correct

iii. Must not exceed 255 characters

1 to 255

iv) Must be unique in the scope of declaration.

Dim a, b, c ‘Correct
Dim d, e ‘Correct
Dim f, g, A ‘Incorrect

7. Scope of Variables

i. Script Level Variables

They can be used for entire script.

ii. Function Level Variables

They can be used within the Functions only

Example:

Dim a, b, c ‘Script level variables
a = 10
b = 20
c = a + b
Msgbox c ’30
Function xyz()
Dim d, e ‘Function level variables
d = 40
e = a + d
Msgbox e ’50
End Function
Call xyz()
Dim f, g ‘Script level variables
f = 70
g = b + d + f
Msgbox g ’90
—————————-
Option Explicit
Dim a, b, c ‘Script level variables
a = 10
b = 20
c = a + b
Msgbox c ’30
Function xyz()
Dim d, e ‘Function level variables
d = 40
e = a + d
Msgbox e ’50
End Function
Call xyz()
Dim f, g ‘Script level variables
f = 70
g = b + d + f
Msgbox g ‘Error

8. Types of Variables

i. Scalar Variable

To store one value at a time, Value may vary throughout the Execution.

ii. Array Variable

To store series of values at a time based on size of the Array.

Declare Array variable:

Dim a, b(3)
b(0) = 10
b(1) = “abcd”
b(2) = 1.34
b(3) = 40
a = b(0) + b(3)
Msgbox a ’50
———————-
Dim a, b(3)
b(0) = 10
b(1) = “abcd”
b(2) = 1.34
b(3) = 40
b(4) = 50 ‘Error
a = b(0) + b(3)
Msgbox a ’50
———————-
Dynamic Array

Dim a, b(3), c()
ReDim c(3)
c(0) = 10
c(1) = 20
c(2) = 30
c(3) = 40
a = c(1) + c(2)
Msgbox a ’50
ReDim c(5)
c(4) = 50
c(5) = 60
a = c(3) + c(5)
Msgbox a ’60
———————-
Use Preserve keyword

Dim a, b(3), c()
ReDim c(3)
c(0) = 10
c(1) = 20
c(2) = 30
c(3) = 40
a = c(1) + c(2)
Msgbox a ’50
ReDim Preserve c(5)
c(4) = 50
c(5) = 60
a = c(3) + c(5)
Msgbox a ‘100
———————-
Dimensional Arrays

Dim a, b(3), c(), d(4, 5)
d(0, 0) = 10

Assigning series of Values at a time to Array variables

a. Using Array Function

Dim a
Msgbox IsArray(a) ‘False
a = Array(100, “VBScript”, 20, 30, 40, #10/10/2010#)
Msgbox IsArray(a) ‘True
Msgbox a(1) ‘VBScript
Msgbox UBound(a) ‘5

b. Using Split Function

Dim a, b
a = “VB Script Language”
msgbox isArray(b) ‘False
b = Split(a)
Msgbox IsArray(b) ‘True
Msgbox b(1) ‘Script
Msgbox UBound (b) ‘2
———————-
Dim a, b
a = “VB,Script,Language”
msgbox isArray(b) ‘False
b = Split(a, “,”)
Msgbox IsArray(b) ‘True
Msgbox b(1) ‘Script
Msgbox UBound (b) ‘2
———————-
Dim a, b
a = “VB@Script@Language”
msgbox isArray(b) ‘False
b = Split(a, “@”)
Msgbox IsArray(b) ‘True
Msgbox b(1) ‘Script
Msgbox UBound (b) ‘2
———————-
Dim a, b
a = “VB@%$Script@%$Language”
msgbox isArray(b) ‘False
b = Split(a, “@%$”)
Msgbox IsArray(b) ‘True
Msgbox b(1) ‘Script
Msgbox UBound (b) ‘2
———————-
Note: In Split Function default delimiter is space, we can use any value as a delimiter, but we need to specify the delimiter.


VBScript Operators

Operators are used to performing the mathematical, comparison, and logical operations.

Categories of operators:

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators

Note: Concatenation operators (Part of Arithmetic Operators)

Operator precedence:

Operator precedence is VBScript operator priority process, generally, VBScript evaluate operators from left to right, but if any high priority operator is there in right side then first VBScript evaluate high priority operator then general rule.

Note: In order to override operator precedence, use () symbol

Example:

Msgbox 2 + 2 * 4 ^ 2 ’34
Msgbox (2 + 2) * 4 ^ 2 ’64
——————
Msgbox 2 + 2 * 4 ’10
Msgbox (2 + 2) * 4 ’16

1. Arithmetic Operators

i. Exponentiation ^

ii. Multiplication *

iii. Division /

iv. Integer Division \

v. Mod Operator

vi. Addition +

vii. Subtraction –

viii. Concatenation &

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.33333333333

c = a \ b
Msgbox c ‘3

c = a Mod b
Msgbox c ‘1

c = a + b
Msgbox c ’13

c = a – b
Msgbox c ‘7

c = a & b
Msgbox c ‘103
———————–
+ Operator

Dim a, b, c
a = 10
b = 3
c = a + b
Msgbox c ’13

a = 10
b = “3”
c = a + b
Msgbox c ’13

a = “10”
b = “3”
c = a + b
Msgbox c ‘103

a = “Hydera”
b = “bad”
c = a + b
Msgbox c ‘Hyderabad

a = “Hyderabad”
b = “123”
c = a + b
Msgbox c ‘Hyderabad123

a = “Hyderabad”
b = 123
c = a + b
Msgbox c ‘Error
———————–
& Operator

Dim a, b, c
a = 10
b = 3
c = a & b
Msgbox c ‘103

a = 10
b = “3”
c = a & b
Msgbox c ‘103

a = “10”
b = “3”
c = a & b
Msgbox c ‘103

a = “Hydera”
b = “bad”
c = a & b
Msgbox c ‘Hyderabad

a = “Hyderabad”
b = “123”
c = a & b
Msgbox c ‘Hyderabad123

a = “Hyderabad”
b = 123
c = a & b
Msgbox c ‘Hyderabad123

2. Comparison Operators (All are Equal)

i. >

ii. >=

iii. <

iv. <=

v. =

vi. <>

Note: Comparison operators return Boolean (logical) result.
Ex: True / False
————————-
Example:

Dim a, b, c
a = 10
b = 3
c = a > b
Msgbox c ‘True

c = a >= b
Msgbox c ‘True

c = a <> b
Msgbox c ‘True

c = a < b
Msgbox c ‘False

c = a <= b
Msgbox c ‘False

c = a = b
Msgbox c ‘False

3. Logical Operators

i. Not (Logical Negation)

If Not Dialog(“Login”).Exist(3) Then
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”,””,”C:\Program Files\HP\Unified Functional Testing\samples\flight\app\”,””
End If
Dialog(“Login”).Activate @@ hightlight id_;_525276_;_script infofile_;_ZIP::ssf1.xml_;_
Dialog(“Login”).WinEdit(“Agent Name:”).Set “asdf” @@ hightlight id_;_66772_;_script infofile_;_ZIP::ssf2.xml_;_
Dialog(“Login”).WinEdit(“Password:”).SetSecure “555fe8c872cfa7718d3ea9b61ac921c85ea7371b” @@ hightlight id_;_66774_;_script infofile_;_ZIP::ssf3.xml_;_
Dialog(“Login”).WinButton(“OK”).Click @@ hightlight id_;_66776_;_script infofile_;_ZIP::ssf4.xml_;_

ii. And (Logical Conjunction)

Dim a, b, c
a = 100
b = 90
c = 80

If a > b And a > c Then
Msgbox “A is a Big Number”
Else
Msgbox “A is Not a Big Number”
End If
————————
Result Criteria:

Exp1 Exp2 Result
————————
True True True
True False False
False True False
False False False

3. Or (Logical Disjunction)

Result Criteria:

Exp1 Exp2 Result
————————
True True True
True False True
False True True
False False False

4) XOr (Logical exclusion)

Result Criteria:

Exp1 Exp2 Result
————————
True True False
True False True
False True True
False False False


VBScript Conditional Statements

a. Types of Conditional statements

i. If Statement
ii. Select Case Statement

b. Types of Conditions

i. Single Condition
ii. Compound Condition
iii. Nested Condition

c. Purpose of conditional statements in UFT:

i. To insert verification points
ii. For Error handling

d. Usage of Conditional Statements

i. Execute a statement when the condition is True/ Simple If
ii. Execute a block of statements when a condition is True.
iii. Execute a block of statements when a condition is True, otherwise execute another block of statements.
iv. Decide among several alternates (ElseIf)
v. Execute a block of statements when more than one condition is true. (Nested If)
vi. Decide among several alternates (using select Case)

Examples:

i. Execute a statement when a condition is True/ Simple If

Syntax:

If Condition Then Statement

Example:

Dim myDate
myDate = #10/10/2010#

If myDate < Date Then myDate = Date
Msgbox myDate

myDate = #10/10/2017#

If myDate < Date Then myDate = Date
Msgbox myDate

ii. Execute a block of statements when condition is True.

Syntax:

If Condition Then
Statements
———–
———-
———-
End If

Example:

Dim a, b
a = 100
b = 500

If a > b Then
Msgbox “A is a Big Number”
End If

iii. Execute a Block of statements when condition is True, otherwise execute another block of statements.

Syntax:

If Condition Then
Statements
———–
———–
———–
Else
Statements
———–
———–
———–
End If

Examples:
———–
Dim a, b
a = 100
b = 900

If a > b Then
Msgbox “A is a Big Number”
Else
Msgbox “B is a Big Number”
End If
——————
Dim a, b
a = InputBox(“Enter A Value”)
b = InputBox(“Enter B Value”)

If Cint (a) > Cint (b) Then
Msgbox “A is a Big Number”
Else
Msgbox “B is a Big Number”
End If
——————————-
Dim a, b
a = InputBox(“Enter A Value”)
b = InputBox(“Enter B Value”)

If ISNumeric(a) = True And IsNumeric(b) = True Then
If Cint (a) > Cint (b) Then
Msgbox “A is a Big Number”
Else
Msgbox “B is a Big Number”
End If
Else
Msgbox “Invalid Input”
End If

iv. Decide among several alternates (Else If)

Syntax:

If Condition then
Statements
————-
————
———-
ElseIf Condition Then
Statements
————-
————
———-
ElseIf Condition Then
Statements
————-
————
———-
ElseIf Condition Then
Statements
————-
————
———-
Else
Statements
————-
————
———-
End If

Example:

‘Read a Value and Verify the Range
‘If the value is in between 1 and 100 then display “Value is a Small Number”
‘If the value is in between 101 and 1000 then display “Value is a Medium Number”
‘If the value is in between 1001 and 10000 then display “Value is a Big Number”
‘If the value is more than 10000 then display “Value is High Number”
‘Otherwise display “value is either Zero or Negative value.

VBScript Program:

Dim val
val = InputBox(“Enter a Value”)

If IsNumeric(val) Then
If val >= 1 And val <=100 Then
Msgbox “Value is Small Number”

ElseIf val > 100 And val <= 1000 Then
Msgbox “Value is a Medium Number”

ElseIf val > 1000 And val <= 10000 Then
Msgbox “Value is a Big Number”

ElseIf val > 10000 Then
Msgbox “Value is High Number”

Else
Msgbox “value is either Zero or Negative Value”
End If
Else
msgbox “Invalid Input”
End If

v. Execute a block of statements when more than one condition is True

Syntax:

If Condition Then
If Condition Then
If Condition Then
Statements
———
———–
Else
———-
———
End If
End If
End If

Example:

‘Read a Value and verify whether the Value is Valid Mobile Number or not?
‘Value should be Numeric
‘Value must contain 10 digits
‘First letter should be either 9 or 8

VBScript Program:

Dim val
val = InputBox (“Enter a Value”)

If IsNumeric(val) = True Then
If Len(val) = 10 Then
If Left(val, 1) = 9 Or Left(val, 1) = 8 Then
Msgbox “val is a Valid Mobile Number”
Else
Msgbox “Val is Invalid Mobile Number”
End If
Else
Msgbox “It is not a 10 digit value”
End If
Else
Msgbox “It is not a Numeric Value”
End If

‘Handle . Symbol

vi. Decide among several alternates (using Select Case)

Syntax:

Select Case TestExpression
Case “Case1Name”
Statements
———-
———-
Case “Case2Name”
Statements
———-
———-
Case “Case3Name”
Statements
———-
———-
Case Else
Statements
———-
——–
———-
End select

Example:

Dim a, b, operation
a = 10
b = 20
operation = LCase (InputBox(“Enter a value”))

Select Case operation
Case “add”
Msgbox “Addition of a, b is: “& a+b

Case “sub”
Msgbox “Subtraction of a, b is: “& a-b

Case “mul”
Msgbox “Multiplication of a, b is: “& a*b

Case “div”
Msgbox “Division of a, b is: “& a/b

Case Else
msgbox “Invalid Operation”
End Select


VBScript Loop Statements

1. For…Next
2. While…Wend
3. Do While / Until…Loop
4. For Each…Next

1. For…Next

Description:

It repeats a block of statements for a specified number of times.

Syntax:

For Counter (Variable) = Start to End Step Incr/Decr
Statements
———
———-
———–
Next

Example:

For i = 1 To 5 Step 1
Msgbox i & ” Hello UFT”
Next
———————————————-
For OrderNumber = 1 To 10 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 OrderNumber
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
Next
——————————-
‘ Terminating For loop
For OrderNumber = 20 To 25 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 OrderNumber
Wait 2
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
Window(“Flight Reservation”).WinButton(“Button_2”).Click
Reporter.ReportEvent 3, “Res”, “Up to “& OrderNumber -1 & ” Orders only Exist”
Exit For
End If
Next

2. While…Wend

It repeats a block of statements while a condition is True

Syntax:

While Condition
Statements
———-
———-
———
Incr/Decr
Wend

Example:

OrderNo = 1
While OrderNo <= 5
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 OrderNo
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrderNo = OrderNo + 1
Wend

3. Do While / Until…Loop

Using While Keyword
It repeats a block of statements while a condition is True

Using Until Keyword

It repeats a block of statements Until the condition is True

i.

Do While Condition
Statements
———-
———-
Incr/Decr
Loop

ii.
Do
Statements
———-
———-
Incr/Decr
Loop While Condition
———————————
iii.

Do Until Condition
Statements
———–
————
———-
Incr/Decr
Loop

iv.
Do
Statements
———–
————
———-
Incr/Decr
Loop Until Condition

Examples:

OrderNo = 1
Do While OrderNo <= 5
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 OrderNo
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrderNo = OrderNo + 1
Loop
——————————–
OrderNo = 10
Do
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 OrderNo
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrderNo = OrderNo + 1
Loop While OrderNo <= 5
——————————–
OrderNo = 1
Do Until OrderNo > 5
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 OrderNo
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrderNo = OrderNo + 1
Loop
——————————–
OrderNo = 1
Do
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 OrderNo
Wait 2
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
OrderNo = OrderNo + 1
Loop Until OrderNo > 5
——————————–
‘Terminating Do loop
OrderNo = 20
Do Until OrderNo > 30
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 OrderNo
Wait 2
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
Window(“Flight Reservation”).WinButton(“Button_2”).Click
Reporter.ReportEvent micWarning, “Res”, “Up to “& OrderNo-1 & ” Orders only exist”
Exit Do
End If

OrderNo = OrderNo + 1
Loop

iv. For Each…Next

It executes all elements in an Array.

Syntax:

For Each Element in Array
Statements
———-
———-
Next

Example:

Dim a, b, res(3)
a = 10
b = 20

res(0) = “Addition of a, b is: “& a + b
res(1) = “Subtraction of a, b is: “& a – b
res(2) = “Multiplication of a, b is: “& a * b
res(3) = “Division of a, b is: “& a / b

For Each Element in res
Msgbox Element
Next


VBScript User defined Functions

A Function is a reusable code.

Whenever we want to perform the same operation multiple times then we choose Functions.

Two types of Functions in VBScript:

i. Built-in Functions

Array functions
String functions
I/O Functions
Date & Time Functions
Conversion functions etc….

ii. User-defined Functions

a. Sub Procedures
b. Function Procedures

User-defined Functions

a. Sub Procedures

Set of statements enclosed with Sub and End sub statements to perform an operation.

Sub Procedure takes Arguments, but Arguments are optional.

Sub Procedure won’t return any value.

Syntax:

Sub procedureName (Argumnets)
Statements
———–
———
———
End Sub

b. Function Procedures

Set of statements enclosed with Function and End Function statements to perform an Operation.

Function Procedure takes Arguments, but Arguments are optional

Function Procedure Can return a value.

Syntax:

Function procedureName (Arguments)
Statements
———–
————-
————
End Function

Note: Sub procedures are faster in Execution than Function Procedures.
————————————————————–
Access Modifiers

Public

Private
—————–
Usage of Functions

Internal – Defining and calling within the script

External – Calling from external library files.
———————————
i) Create a Sub Procedure with no Arguments

Sub Login ()
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set “asdf”
Dialog(“Login”).WinEdit(“Password:”).SetSecure “5566695dab8b9f47c06f8ba443bdba84f0d5274e”
Dialog(“Login”).WinButton(“OK”).Click
End Sub
Call Login()
—————————————————
ii) Create a Sub Procedure with Arguments

Sub Login (Agent, Password)
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set Agent
Dialog(“Login”).WinEdit(“Password:”).Set Password
wait 2
Dialog(“Login”).WinButton(“OK”).Click
End Sub
Call Login(“abcd”, “mercury”)
—————————————————
iii) Sub Procedure with Arguments and Data Driven Testing

Sub Login (Agent, Password)
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set Agent
Dialog(“Login”).WinEdit(“Password:”).Set Password
wait 2
Dialog(“Login”).WinButton(“OK”).Click
Window(“Flight Reservation”).Close
End Sub
Call Login(DataTable(1, 1), DataTable(2, 1))
———————————————————
iv) Sub Procedure with Arguments and load Shared object repository file from Function library.

Sub Login (Agent, Password)
RepositoriesCollection.Add “C:\Users\gcreddy\Desktop\login.tsr”
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
Dialog(“Login”).Activate
Dialog(“Login”).WinEdit(“Agent Name:”).Set Agent
Dialog(“Login”).WinEdit(“Password:”).Set Password
wait 2
Dialog(“Login”).WinButton(“OK”).Click
End Sub
——————————————————
v) Sub Procedure with Arguments and Verification Points

Sub Login(Agent, Password)
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
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
Result = “Login Successful – Passed”
Else
SystemUtil.CloseDescendentProcesses
Result = “Login Unsuccessful – Failed”
End If
Msgbox Result
End Sub
Call Login(“abc”, “mercury”)
————————————-
Sub Login(Agent, Password)
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
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
Result = “Login Successful – Passed”
Else
If Dialog(“Login”).Dialog(“Flight Reservations”).Exist(3) Then
Dialog(“Login”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
Dialog(“Login”).WinButton(“Cancel”).Click
Result = “Login Unsuccessful – Failed”
End If
End If
Msgbox Result
End Sub
Call Login(“abc”, “mercury”)

‘Function Procedure with returning value
Function Login(Agent, Password)
SystemUtil.Run “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
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 Successful – Passed”
Else
If Dialog(“Login”).Dialog(“Flight Reservations”).Exist(3) Then
Dialog(“Login”).Dialog(“Flight Reservations”).WinButton(“OK”).Click
Dialog(“Login”).WinButton(“Cancel”).Click
Login = “Login Unsuccessful – Failed”
End If
End If
End Function
res = Login(“abcd”, “mercury”)
Msgbox res
————————————————–
Note:
If we use local (Function level) variable then we can use the value within the Function only.

If we return (Function Name) the value then we can use the value within the Function and
we can pass the value to external functions and export the value to external files.
————————————————————
‘Function Procedure with returning multiple values

Function Verify_UpdateButton()
Dim Before_Open, After_Open, Verify1, Verify2

Window(“Flight Reservation”).Activate
Before_Open = Window(“Flight Reservation”).WinButton(“Update Order”).GetROProperty(“enabled”)

If Before_Open = False Then
Verify1 = “Update Button Disabled -Passed”
Else
Verify1 = “Update Button Enabled -Failed”
End If

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 “1”
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
After_Open = Window(“Flight Reservation”).WinButton(“Update Order”).GetROProperty(“enabled”)

If After_Open = True Then
Verify2 = “Update Button Enabled – Passed”
Else
Verify2 = “Update Button Disabled – Failed”
End If
Verify_UpdateButton = Array(Verify1, verify2)
End Function
Result= Verify_UpdateButton()
Msgbox Result(0)
Msgbox Result(1)

‘Calling a Function within the Function
Function OpenOrder(OrderNo)
Call Login(“abcd”, “mercury”)
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 OrderNo
Window(“Flight Reservation”).Dialog(“Open Order”).WinButton(“OK”).Click
End Function
Call OpenOrder(7)


VBScript Built-in Functions

1. Asc Function

Returns ANSI character code for first letter of a String or number.

‘A to Z (65 to 90)

‘a to z (97 to 122)

‘0 to 9 (48 to 57)

Ex:
Dim val
val = “ABCD”
Msgbox Asc(val) ’65
Msgbox Asc(“ABCD”) ’65
Msgbox Asc(“Z”) ’90
Msgbox Asc(“a”) ’97
Msgbox Asc(“z”) ‘122
Msgbox Asc(1) ’49
Msgbox Asc(“*”) ’42

2. Chr Function

Returns Character value for ANSI character code

Ex:
Msgbox Chr(65) ‘A
Msgbox Chr(90) ‘Z
Msgbox Chr(97) ‘a
Msgbox Chr(122) ‘z
Msgbox Chr(49) ‘1
Msgbox Chr(42) ‘*

3. Abs Function

Returns absolute value (Positive value).

Msgbox Abs (100.34) ‘100.34
Msgbox Abs (100.74) ‘100.74
Msgbox Abs (-100.34) ‘100.34

4. Round Function

Rounds the value to nearest integer.

Ex:
Msgbox Round(100.34) ‘100
Msgbox Round(100.74) ‘101
Msgbox Round(-100.34) ‘-100

5) Array Function

It assigns Series of values at a time to a variable

ex:
Dim a
Msgbox IsArray(a) ‘False
a = Array(1, 2, 3, “abcd”, 2.34)
Msgbox IsArray(a) ‘True
msgbox a(1) ‘2
Msgbox UBound (a) ‘4

6) IsArray Function

Checks weather the Variable is Array variable or not?
Return Boolean (Logical) Result.

Ex:
Dim a, b(3), c(), d(4, 5)
Msgbox IsArray(a) ‘False
Msgbox IsArray(b) ‘True
Msgbox IsArray(c) ‘True
Msgbox IsArray(d) ‘True

7) IsNumeric

Checks weather the value is Numeric value or not?

Msgbox isNumeric(100) ‘True
Msgbox isNumeric(“100”) ‘True
Msgbox isNumeric(“abcd”) ‘False
Msgbox isNumeric(1.345) ‘True
Msgbox isNumeric(#10/10/2010#) ‘false

8) IsDate

Checks weather the value is Data type data or not?

Ex:
Msgbox IsDate(100) ‘False
Msgbox IsDate(“abcd”) ‘False
Msgbox IsDate(1.345) ‘false
Msgbox IsDate(#10/10/2010#) ‘True
Msgbox IsDate(#10/10/10#) ‘True
Msgbox IsDate(#Sep/10/2010#) ‘True
Msgbox IsDate(#December/10/2010#) ‘True

9) IsEmpty

Checks weather the variable is empty variable or not?

Dim val
Msgbox IsEmpty(val) ‘True
val = 0
Msgbox IsEmpty(val) ‘False
val = Empty
Msgbox IsEmpty(val) ‘True

10) Date Function

Returns current System Date.

11) Time Function

Returns current System Time.

12) Now Function
Returns current System Date & Time.

Example:

Dim a
a = Date
Msgbox a

Msgbox Date

Msgbox Time

Msgbox Now

msgbox Date &” “& Time

Msgbox Time &” “& Date

13) Datediff Function

Returns Date difference between two dates based on interval.

It deducts first date from second date.

Ex:
Dim date1, date2
date1 = #10/10/2010#
date2 = #10/10/2012#

Msgbox Datediff(“yyyy”, date1, date2) & ” Years”

Msgbox Datediff(“q”, date1, date2) & ” Quarters”

Msgbox Datediff(“m”, date1, date2) & ” Months”

Msgbox Datediff(“w”, date1, date2) & ” Weeks”

Msgbox Datediff(“d”, date1, date2) & ” Days”

Msgbox Datediff(“h”, date1, date2) & ” Hours”

Msgbox Datediff(“n”, date1, date2) & ” Minutes”

Msgbox Datediff(“s”, date1, date2) & ” Seconds”

14) Left Function

Returns a specified number of charactors from left side of a string or number.

ex:

Dim val
val = 9249012345
msgbox Left(val, 5) ‘92490

Msgbox Left(“Hyderabad”, 3) ‘Hyd
Msgbox Left(123.456, 4) ‘123.
Msgbox Left(#10/10/2010#, 5) ’10/10

15) Right Function

Returns a specified number of characters from right side of a string or number.

Ex:
Dim val
val = 9249012345
msgbox Right(val, 5) ‘12345

Msgbox Right(“Hyderabad”, 3) ‘bad
Msgbox Right(123.456, 4) ‘.456
Msgbox Right(#10/10/2010#, 5) ‘/2010

16) Mid Function

Returns a specified number of characters from a string or number.

Ex:
Msgbox Left(“Hyderabad”, 3) ‘Hyd
Msgbox Mid(“Hyderabad”, 1, 3) ‘Hyd

Msgbox Right(“Hyderabad”, 3) ‘bad
Msgbox Mid(“Hyderabad”, 7) ‘bad

Msgbox Mid(“Hyderabad”, 4, 3) ‘era

17) Trim

18) LTrim

19) RTrim

Ex:
Dim val
val =” VBScript ”
msgbox val

Msgbox Trim(val)
Msgbox LTrim(val)
Msgbox RTrim(val)

20) LCase Function

Converts Upper case values to lower case.

Ex:

Dim val
val = “HYDERABAD”
Msgbox LCase(val) ‘hyderabad
Msgbox LCase(“HYDERABAD”) ‘hyderabad
Msgbox LCase(“hyderabad”) ‘hyderabad
Msgbox LCase(“HYDerabad”) ‘hyderabad
Msgbox LCase(“HYD123”) ‘hyd123
Msgbox LCase(123) ‘123

21) UCase Function

Converts Lower case values to Upper case

Ex:

Dim val
val = “HYDERABAD”
Msgbox UCase(val) ‘HYDERABAD
Msgbox UCase(“HYDERABAD”) ‘HYDERABAD
Msgbox UCase(“hyderabad”) ‘HYDERABAD
Msgbox UCase(“HYDerabad”) ‘HYDERABAD
Msgbox UCase(“HYD123”) ‘HYD123
Msgbox UCase(123) ‘123

22) Cint Function

Converts String type data into Integer sub type.

When Conversion is required?

Whenever we read data then VBScript considers as String type data, in order to perform
mathemetical calculations we need to convert the data.

Ex:

Dim val, Tickets
val = InputBox (“Enter a Value”)
Msgbox VarType(val) ‘8 for String
val = Cint(val)
Msgbox VarType(val)

Tickets = Window(“Flight Reservation”).WinEdit(“Tickets:”).GetROProperty(“text”)
Msgbox VarType(Tickets) ‘8 for string
Msgbox VarType(Cint (Tickets)) ‘2 for Integer

Note: We can’t convert Alfa bytes into Integer sub type or double sub type.

23) Cdbl Function

Converts String type data into double sub type.

Ex:
Dim val, Price
val = InputBox (“Enter a Value”)
Msgbox VarType(val) ‘8 for String
val = Cdbl(val)
Msgbox VarType(val)

Price = Window(“Flight Reservation”).WinEdit(“Price:”).GetROProperty(“text”)
msgbox VarType(Price) ‘8 for String
Msgbox VarType(Cdbl(Price)) ‘5 for Double

24) VarType Function

It checks data sub type and returns constant based result.

Ex:

Dim a, b(3)
Msgbox VarType(a) ‘0 for Empty / Uninitialized
a = 100
Msgbox VarType(a) ‘2 for Integer
a = “100”
Msgbox VarType(a) ‘8 for String

Msgbox VarType(“abcd”) ‘8
Msgbox VarType(1.234)’5 for Double
Msgbox VarType(#10/10/2010#) ‘7 for date
Set a = CreateObject(“Scripting.FilesystemObject”)
Msgbox varType(a) ‘9 for Automation object
Msgbox varType(b)
b(0) = “abc”
b(1) = 123
b(2) = 1.23
b(3) = #10/10/2010#
Msgbox varType(b(0))’ 8
Msgbox varType(b(1)) ‘2
Msgbox varType(b(2))’5
Msgbox varType(b(3)) ‘7

25) Len Function

It checks length of a string or number.

Ex:

Dim a
a = “INDIA”
Msgbox Len(a) ‘5
Msgbox Len(“INDIA”) ‘5
Msgbox Len(120) ‘3
Msgbox Len(1.234) ‘5
Msgbox Len(#10/10/2010#) ’10
Msgbox Len(#10/10/10#)’10
Msgbox Len(#Sep/10/2010#) ‘9
Msgbox Len(#December/10/2010#) ’10

26) Split Function

Splits a String based on delimiter, default delimiter is space.

Dim a, b
a = “VB Script Language”
b = Split(a)
Msgbox IsArray(b)’True
Msgbox b(1) ‘Script

Dim a, b
a = “VB,Script,Language”
b = Split(a, “,”)
Msgbox IsArray(b)’True
Msgbox b(1) ‘Script

Dim a, b
a = “VB#$%Script#$%Language”
b = Split(a, “#$%”)
Msgbox IsArray(b)’True
Msgbox b(1) ‘Script

27) Join Function

Joins all elements of Array variable.

Ex:
Dim a(2)
a(0) = “VB”
a(1) =”Script”
a(2) = “Language”
Msgbox Join(a)
—————-
Dim a(2)
a(0) = “VB”
a(1) =”Script”
a(2) = “Language”
Msgbox Join(a,”@”)

28) Lbound, UBound Functions

Lbound Returns lower boundary of Array

UBound Returns upper boundary fo Array

Ex:
Dim a, b(3)
a =Array (1, 2, 3, 4, 5, 2.3, “abc”)
Msgbox LBound(a)’0
Msgbox UBound(a)’6

b(1) = 1
b(2) = 2
b(3) = 1.2
Msgbox LBound(a)’0
Msgbox UBound(a)’6

29) StrComp Function

It compares two strings based on compare mode.

It supports 3 way comparison

Two way comparison – True/False
Three way comparison – >, <, =

Compare modes

0 for Binary (based on ANSI character codes) comparison

1 for Textual comparison

Note:

Default compare mode is Binary mode.

Result Criteria:

if str1 > str2 then 1
if str1 < str2 then -1
if str1 = str2 then 0

Example:

Dim str1, str2
str1 = “UFT”
str2 = “uft”

Msgbox StrComp(str1, str2, 0) ‘-1
Msgbox StrComp(str1, str2) ‘-1
Msgbox StrComp(str1, str2, 1) ‘0

str1 = “uFT”
str2 = “Uft”

Msgbox StrComp(str1, str2, 0) ‘1
Msgbox StrComp(str1, str2) ‘1
Msgbox StrComp(str1, str2, 1) ‘0

30) InputBox Function

31) MsgBox Function

Dim val
val = InputBox (“Enter a Value”)
Msgbox “Value is: “& val

a = 100
b = 200
Msgbox “Hello UFT”
Msgbox “Hello UFT ” & a
Msgbox “hello UFT ” & a & ” Hello VBScript”
msgbox a & b

32) CreateObject Function

creats an Automation object in a specified class.

Syntax:

Set variable = CreateObject(“Class Value”)

Ex:

Dim objFso, objExcel, objWord, objConnection, objRecordset, objDictionary, objQTP

‘Create File system object, it is used to work with Drives, Folders and Files.
Set objFso = CreateObject(“Scripting.FileSystemObject”)

‘Create excel Application object, It is used to perform operations on Excel Application
Set objExcel = CreateObject(“Excel.Application”)

‘Create Word Application object, It is used to perform opertions on Word Application
Set objWord = CreateObject(“Word.Application”)

‘Create Database Connection object, It is used to connect to a database
Set objConnection = CreateObject(“Adodb.Connection”)

‘Create Database Recordset object, It is used to perform operations on database records
Set objRecordset = CreateObject(“Adodb.Recordset”)

‘Create dictionary object, It is used to define key, value pairs
Set objDictionary = CreateObject(“scripting.Dictionary”)

‘Create QTP Application object, It is used to automate UFT tool operations
Set objQTP = CreateObject(“QuickTest.Application”)


File System Operations

What is Computer File System?

It is a feature of the operating system, used to work with Drives, Folders, and Files.

Examples for File System operations

Create a Folder

Copy a Folder

Delete a Folder

Create a Text file

Delete a Text file

Read data

Write data

Compare data

Search for data etc…

How end-user performs File system Operations?

End-user performs File system operations manually with the help of Input devices if it is command-line operating system with the help of OS commands.

How to perform automatic file system operations in VBScript?

Using File system Object we can perform automatic File system operations.

Create File System Object

Set objFso = CreateObject(“Scripting.FileSystemObject”)

Set – VBScript Statement

objFso – Variable

CreateObject – VBScript Built in Function

“Scripting.FileSystemObject” – Class Value

Note: Class value only varies from one object model to another.

Examples:

1. Create a Folder

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)
objFso.CreateFolder “C:\Users\gcreddy\Desktop\QTP”
Set objFso = Nothing ‘To release the memory

Note:

Set objFso = Nothing statement for releasing the memory immediatly, otherwise memory
will be released after re-launching the UFT tool.

It is not mandatory statement, but best practice (Standard)

Follow the three steps:

i. Create Automation Object
ii. Use Object
iii. Close Object

2) Check the existence of QTP folder, if not exists then create the folder.

Dim objFso, FolderPath
FolderPath = “C:\Users\gcreddy\Desktop\QTP”
Set objFso = CreateObject(“Scripting.FileSystemObject”)

If Not objFso.FolderExists(FolderPath) Then
objFso.CreateFolder Folderpath
End If

Set objFso = Nothing

3) Copy a Folder

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)
objFso.CopyFolder “C:\Users\gcreddy\Desktop\QTP”, “C:\”

Set objFso = Nothing
—————
Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)
objFso.CopyFolder “C:\Users\gcreddy\Desktop\QTP”, “C:\UFT”

Set objFso = Nothing

4) Delete a Folder

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)
objFso.DeleteFolder “C:\Users\gcreddy\Desktop\QTP”
Set objFso = Nothing

5) Check the existence of QTP folder, if exists then delete the folder.

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)

If objFso.FolderExists(“C:\Users\gcreddy\Desktop\QTP”) Then
objFso.DeleteFolder “C:\Users\gcreddy\Desktop\QTP”
End If

Set objFso = Nothing

6) Create a Text file

Note: File System Object is only used for Drives, Folders and Flat files.
We can create and delete other types of also, but we can’t perform internal operations like Reading, Writing etc…

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)

objFso.CreateTextFile “C:\Users\gcreddy\Desktop\QTP.txt”
objFso.CreateTextFile “C:\Users\gcreddy\Desktop\QTP.doc”
objFso.CreateTextFile “C:\Users\gcreddy\Desktop\QTP.xls”
objFso.CreateTextFile “C:\Users\gcreddy\Desktop\QTP.pdf”

Set objFso = Nothing

7) Delete a Text file

Dim objFso
Set objFso = CreateObject(“Scripting.FileSystemObject”)

objFso.DeleteFile “C:\Users\gcreddy\Desktop\QTP.txt”
objFso.DeleteFile “C:\Users\gcreddy\Desktop\QTP.doc”
objFso.DeleteFile “C:\Users\gcreddy\Desktop\QTP.xls”
objFso.DeleteFile “C:\Users\gcreddy\Desktop\QTP.pdf”

Set objFso = Nothing

External Operations

Create a Text file

Delete a Text file

Check existence of a File

Count size

etc…

Internal operations

Read
Read character by Character
Read Line by Line
Read All

Write
Write Continuously
Write Line by Line
Append

Compare
Compare two text files by Size (*External operation)
Compare two text files by Text
Compare two text files by Binary values.

Search operations

> using the File System object we can perform External File operations

> Using Text stream object we can perform Internal operations.

> Using File System Object we can create Text stream object.

Create File System Object
Set Variable = CreateObject(“Scripting.FileSystemObject”)

Create a Text Stream object

Set Variable = FileSystemObject.CreateTextFile / OpenTextFile(“File path”, File mode)

File Modes for Text files

i. 1 for Read
ii. 2 for Write
iii. 8 for Append

Note: Read mode is the default mode.

Examples:

8) Read a Text File Character by Character

Dim objFso, objTextstream, myChar
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextstream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\QTP.txt”)

Do While objTextstream.AtEndOfStream = False
myChar = objTextstream.Read(1)
Msgbox myChar
Loop
objTextstream.Close
Set objTextstream = Nothing
Set objFso = Nothing

9) Read a Text File Line by Line

Dim objFso, objTextstream, myLine
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextstream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\QTP.txt”)

Do While objTextstream.AtEndOfStream = False
myLine = objTextstream.ReadLine
Msgbox myLine
Loop
objTextstream.Close
Set objTextstream = Nothing
Set objFso = Nothing

10) Read a text file (read all)

Dim objFso, objTextstream, myContent
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextstream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\QTP.txt”)

Do While objTextstream.AtEndOfStream = False
myContent = objTextstream.ReadAll
Msgbox myContent
Loop
objTextstream.Close
Set objTextstream = Nothing
Set objFso = Nothing
——————————————
Dim objFso, objTextstream, myContent
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextstream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\UFT.txt”)

Do While objTextstream.AtEndOfStream = False
myContent = objTextstream.ReadAll
Print myContent
Loop
objTextstream.Close
Set objTextstream = Nothing
Set objFso = Nothing
————————————-
Note: Print command is not a Global VBScript command, it is only for UFT.

11) Write data to a Text file

Dim objFso, objTextstream, num1, num2, result
num1 = 10 : num2 = 30 : result = num1 + num2
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextStream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\testdata.txt”, 2)

objTextStream.Write “Addition of num1, num2 is: ” & result

objTextstream.Close
Set objTextStream = Nothing
Set objFso = Nothing

12) Append data to a Text file

Dim objFso, objTextstream, num1, num2, result
num1 = 10 : num2 = 60 : result = num1 + num2
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextStream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\testdata.txt”, 8)

objTextStream.Write “Addition of num1, num2 is: ” & result

objTextstream.Close
Set objTextStream = Nothing
Set objFso = Nothing
——————————
Dim objFso, objTextstream, num1, num2, result
num1 = 10 : num2 = 80 : result = num1 + num2
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextStream = objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\testdata.txt”, 8)

objTextStream.WriteLine “Addition of num1, num2 is: ” & result

objTextstream.Close
Set objTextStream = Nothing
Set objFso = Nothing


VBScript Excel Object Model

Excel Application operations using Excel Application Object

Excel Application Object: It is used to perform operations on Excel Application.

Create Excel Application Object:

Set Variable = CreateObject(“Excel.Application”)
———————-
Excel Application
Excel Workbook / File
Excel Worksheet / Sheet

Excel File Operations using VBScript Examples:

1) Create an Excel file

Dim objExcel
Set objExcel = CreateObject(“Excel.Application”)
objExcel.Visible = True ‘To view the operation (Creating Excel file) during Execution.

objExcel.Workbooks.Add ‘Create New Workbook / file

objExcel.ActiveWorkbook.SaveAs “C:\Users\gcreddy\Desktop\QTP.xls” ‘Save the Excel workbook /file

objExcel.Quit ‘To close the Excel Application
Set objExcel = Nothing ‘To release the memory

2) Check the existence of QTP file, if not exist then create the file.

Dim objFso, objExcel, FilePath
FilePath = “C:\Users\gcreddy\Desktop\QTP.xls”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add ‘Create New Workbook / file
objExcel.ActiveWorkbook.SaveAs FilePath
objExcel.Quit
End If

Set objExcel = Nothing ‘To release the memory

3) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Excel Application Object only)

Dim objFso, objExcel, FilePath

FilePath = “C:\Users\gcreddy\Desktop\QTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
objExcel.Workbooks.Add
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.SaveAs FilePath
Else
objExcel.Workbooks.Open (FilePath)
objExcel.Worksheets(1).Cells(1, 1) = “Hello UFT”
objExcel.ActiveWorkbook.Save
End If
objExcel.Quit

Set objExcel = Nothing

Excel Objects

1) Excel Application Object
It is used to perform operations on Excel Application.

Set Variable = CreateObject(“Excel.Application”)
——————————–
Excel Workbook object
It is used to work with specified Excel file / Workbook

Set Variable = ExcelApplicationObject.Workbooks.Add / Open(“Filepath”)

Excel Worksheet object
It is used to work with specified work sheet

Set Varaible = ExcelWorkbookObject.Worksheets(Sheet Id / “Sheet name”)
——————————————————-
Excel Application is always only one.

We may have one or more Workbooks.

We may have multiple sheets in every workbook.
———————————————
> Using (“Excel.Application”) class value we create Excel Application Object.

> We create Excel Workbook object using Excel Application Object.

> We create Excel Worksheet object using Excel workbook object.
————————————–
Difference between File system object model and Excel object model in case of Sub objects.

In File system object model creating Text stream object is mandatory to perform File internal operations like Read, Write, Compare, Search etc…

In Excel Object model creating sub and sub-sub objects optional, if you want to work with multiple files and multiple sheets then we can use sub and sub-sub objects.

4) Check the existence of QTP file, if exists then open the file and enter some data, If not exist then create the file and enter some data (Using Main and sub objects)

Dim objFso, objExcel, objWorkbook, objWorksheet, FilePath

FilePath = “C:\Users\gcreddy\Desktop\QTP.xlsx”
Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objExcel = CreateObject(“Excel.Application”)

If Not objFso.FileExists(FilePath) Then
Set objWorkbook = objExcel.Workbooks.Add
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.SaveAs FilePath
Else
Set objWorkbook = objExcel.Workbooks.Open (FilePath)
Set objWorksheet = objworkbook.Worksheets(1)
objWorksheet.Cells(1, 1) = “Hello UFT”
objWorkbook.Save
End If
objExcel.Quit

Set objExcel = Nothing

5) Read data from an Excel file and Compare 2 Columns (One to One Binary Comparison).

Dim objExcel, objWorkbook, objWorksheet, i, RowsCount
Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:\Users\gcreddy\Desktop\abcd.xls”)
Set objWorksheet = objWorkbook.Worksheets(1)

RowsCount = objWorksheet.UsedRange.Rows.Count
For i = 2 To RowsCount Step 1
Expected = objWorksheet.Cells(i, 1)
Actual = objWorksheet.Cells(i, 2)

If Expected = Actual Then
objWorksheet.Cells(i, 3) = “Passed”
Else
objWorksheet.Cells(i, 3) = “Failed”
End If
Next
objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing


Database Objects in VBScript

1. ADO Connection Object

The Database Connection Object is used to connect to a Database (any database).

Note: Connection string only varies from one database to another.

Create Database Connection Object

Set Variable = CreateObject(“Adodb.Connection”)

2. ADO Database Recordset object

The Database Recordset object is used to perform operations on Database Tables (Records)

Create Database Recordset Object

Set Variable = CreateObject(“Adodb.Recordset”)

3. ADO Command Object

The Database 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.

Create Database Command Object

Set objCommand=Server.CreateObject(“ADODB.command”)

Examples:

1. Export data from a database to an Excel file.

Dim objConnection, objRecordset, RecordCount
Dim objExcel, objWorkbook, objWorksheet

Set objConnection = CreateObject(“Adodb.Connection”)
Set objRecordset = CreateObject(“Adodb.Recordset”)
objConnection.Provider = (“Microsoft.Jet.OLEDB.4.0”)
objConnection.Open “C:\Users\gcreddy\Desktop\testdb.mdb”
objRecordset.Open “Select Agent, Password from Login”,objConnection

Set objExcel = CreateObject(“Excel.Application”)
Set objWorkbook = objExcel.Workbooks.Open(“C:\Users\gcreddy\Desktop\abcd.xls”)
Set objWorksheet = objWorkbook.Worksheets(1)

objWorksheet.Cells(1, 1) = “Agent”
objWorksheet.Cells(1, 2) = “Password”

i = 2
Do Until objRecordset.EOF = True
objWorksheet.Cells(i, 1) = objRecordset.Fields(“Agent”)
objWorksheet.Cells(i, 2) = objRecordset.Fields(“Password”)
objRecordset.MoveNext
i = i + 1
Loop

objWorkbook.Save
objExcel.Quit

Set objWorksheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing

objRecordset.Close
objConnection.Close

Set objRecordset = Nothing
Set objConnection = Nothing

2. Export data from a database to a Text file.

Dim objConnection, objRecordset, RecordCount
Dim objFso, objTextstream

Set objConnection = CreateObject(“Adodb.Connection”)
Set objRecordset = CreateObject(“Adodb.Recordset”)
objConnection.Provider = (“Microsoft.Jet.OLEDB.4.0”)
objConnection.Open “C:\Users\gcreddy\Desktop\testdb.mdb”
objRecordset.Open “Select Agent, Password from Login”,objConnection

Set objFso = CreateObject(“Scripting.FileSystemObject”)
Set objTextstream =objFso.OpenTextFile(“C:\Users\gcreddy\Desktop\xyz.txt”, 2)

objTextstream.WriteLine “Agent Password”

Do Until objRecordset.EOF = True
objTextstream.WriteLine objRecordset.Fields(“Agent”) &”, “& objRecordset.Fields(“Password”)
objRecordset.MoveNext
Loop

objTextstream.Close
Set objTextstream = Nothing
Set objFso = Nothing

objRecordset.Close
objConnection.Close

Set objRecordset = Nothing
Set objConnection = Nothing


Dictionary Object

Dictionary Object is used to define key, value pairs.

It is equivalent to Associated Array in Perl Script.

VBScript vs. Perl in the case of Variables.

VBScript                              Perl
—————————————–
Scalar Variables               Scalar Variables
Array Variables                Array variables
Dictionary Object            Associated Arrays / Hash Variables

Array vs. Associate Array
In case of Arrays user can define values only, keys (Indexes) are pre-defined.

Din a(3)
a(0) = “India”
a(1) = 100
a(2) = #10/10/2010#
a(3) = “abcd”

Index Values
or
Key
——————–
In case of Associated Array/Dictionary object user can deine key, value pairs.

Dictionary Object Example:

Dim objDictionary
Set objDictionary = CreateObject(“Scripting.Dictionary”)

objDictionary.Add “Agent”, “Hyderabad”
objDictionary.Add “Password”, “mercury”
objDictionary.Add “AppPath”, “C:\Program Files\HP\Unified Functional Testing\samples\flight\app\flight4a.exe”
objDictionary.Add 1, 100
objDictionary.Add “*”, “abc”
objDictionary.Add “d”, #10/10/2012#

Msgbox objDictionary.Count ‘6

objDictionary.Remove(“*”)
Msgbox objDictionary.Count ‘5

Msgbox objDictionary.Exists(“d”) ‘True
Msgbox objDictionary.Exists(“a”) ‘False

objDictionary.RemoveAll
Msgbox objDictionary.Count ‘0


Debugging VBScript Programs

1. What is Debugging?

Locating and isolating Errors through Step by Step execution is called Debugging.

Note: Debugging Scripts is Optional.

2. When is Debugging Required?

Scenario 1:

The script is not showing errors and providing correct Output – Debugging is not required.

Scenario 2:

The script is showing errors- Debugging is optional

Note: First correct the errors then most of time we can get correct output, otherwise
we can debug the script.

Scenario 3:
The script is not showing errors and not providing correct Output – Debugging is required.

Note: Whenever Script is not showing any errors and not providing correct output then
Debugging is required.

3. How to Debug Scripts?

Using VBScript debug commands and breakpoints we can debug scripts.

Important Debug Commands:

a. Step Into (F11)

1) It starts the Script Execution.
2) It executes one statement at a time.
3) If is function call, opens the function and executes one function statement at a time.

b. Step Over (F10)

1) It executes one statement at a time.
2) If it is a function call, it executes all function statements at a time.

Note: Once we open the function using “Step Into” command then “Step Over” executes
one statement(function) at a time only.

c. Step Out (Shift + F11)

1) It executes all remaining function statements at a Time.

d. Breakpoints (F9)

Example:

Dim a, b, c
a = 10
b = 20
c = a+b
a = 5
b = 7
c = a*b
Call Login(“gcreddy”, “mercury”)
a = 20
b = 3
c = a^b
a = 5
b = 7
c = a-b
a =100


Error Handling in VBScript

Handling expected and unexpected Errors

Expected Errors:

Whenever we use Invalid input then we can expect Errors.

Note: We use Invalid input for Negative Testing.

Unexpected Errors:

i. Resource missing

ii. Insufficient Resource

iii. Resource Response

How to Handle Errors:

i. Using Conditional Statements

ii. Using some built-in Functions

iii. Using Exit Statement

iv. Using Option Explicit Statement

v. On Error Statement
Etc,

Follow me on social media:

1 thought on “VBScript Tutorial for Beginners”

Comments are closed.