VB Script For QTP Guide
VB Script For QTP Guide
Scripting: Scripting on the other hand does not involve in writing the entire code
for the application but involves in writing some lines of code or instructions so as to
validate the application developed. To put in simple language Scripting is used for
validation.
Compiler: Programming uses compiler to compiles the entire code in one go and
creates an executable file. This executable file will be used for execution. The
advantage of compiler is that it has a faster execution rate compared to the
interpreter. The big disadvantage of compiler is that there is no way you can
change your code in the executable file and you have to go back to the code and
make changes and again create an executable file.
Interpreter: Scripting uses Interpreter to read the code one line at a time and
executes one line at a time. The advantage is that if the interpreter encounters an
error it stops executing the remaining lines and you have the chance to correct it
and re run it. At any point of time you can interrupt wile running and change the
code and continue running it. The biggest disadvantage is that each time the code
is executed it has to read each line and is time consuming and is also slow.
What is VB Script?
It is very simple to create a VB script. Just write the code in a Microsoft Note pad
and save the file by giving the file name with an .vbs extension. For example in the
File name text box while saving you can enter this file name “example1.vbs”. In the
Save as File choose the option “All Files” other wise it will save as a text file. As
soon as you save your file as a VB script file you can run the script by double
clicking on it.
Step 3: On the desktop or the location you have given you will see a file with this
icon
Step 4: Double clicking on this file your message box will be displayed with the
predefined message you gave “This is First VB Script”
Let’s understand what Msgbox function does
Msgbox is used for displaying the output. It is an inbuilt VB function used to output
(display) a value to the user. This value can be a constant or a variable. Msgbox
contains a OK button. Until the user clicks the OK button the execution will not
move on to the next line.
When you execute the file by double clicking it is displayed like this.
“UserInput” in the above statement is a variable and whatever the user enters in
the text box is stored in the variable called “UserInput”. If we want to view the data
entered on the screen then we need to call this variable in the Msgbox function and
the variable value is displayed for the user. In order to do this modify your code like
this
To put in as a definition Input box is an inbuilt VB Scrip function used for getting an
input from the user during runtime. Input box provides a text box and allows the
user to type in some data. When the user clicks the OK button this data is assigned
to a variable. The default input type for an input box is a string.
What is a Variable?
A variable in the VB script cannot start with a numeric value (Ex – 1stvalue). It can
be a combination of Alphabets and Numbers together (Value1) or separated by a
underscore (Value_1). There is no way you can use arithmetic operators and also
space is not allowed because if space is given then VB script will recognize them as
two different variables. Below are the basic rules followed while creating a Variable.
1.ImplicitDeclaration.
2. Explicit Declaration.
Example
Value1=20
Jobtype=“Permanent”
From the above we can see that = is an assignment operator. The left hand side of
the expression is the variable name and the right hand side of the expression is the
value assigned to the variable.
Implicit Declaration:
Example
Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod
From the above example Int1 and Int2 are operands and the * is the operator and =
is the assignment operator. Int1, Int2, Prod are Implicit Variables and as the script is
executed in the memory the variables get created in the memory and the
respective values are stored in those locations. With this type of declaration it is
easy to create variables as and when required.
The one disadvantage of Implicit variables is that if there is a typo error in any line
like for example "Prod" is mistyped as "Prd" then when the scrip is executed it
creates another variable called "Prd" and the resultant out put is null (Nothing will
be displayed). We should be careful in using the Implicit Declarations.
Explicit Declaration
Explicit Declaration is used to avoid the
unnecessary confusion created while typing
and also to avoid loading the memory with
variables because of errors we can use
Explicit Declaration. In order to use
explicit declaration type we need to declare
the variables before the script begins or it
should be in the starting of the script.
We will use the same example used for Implicit Declaration but will change the
script. In order to create Explicit Declaration in the beginning of the code we need
to add one more line of code as ‘Option Explicit”. Take a look at the code for Explicit
Declaration
Option Explicit
Dim Int1, Int2, Prod
Int1 = 28
Int2 = 30
Prod = Int1 * Int2
Msgbox Prod
Now lets debug the code. If by mistake instead of “Prod” you type “Prd” in Line 6 as
Msgbox Prd then what will happen. Since “Prd” is not declared when you run the
script it executes the first five line and when it executes the sixth line it throws error
and till it is not rectified the resultant output is not displayed. It will throw error as
“Variable is undefined: ‘Prd’.
Variant Subtypes
Variant can hold any type of data like Integer, String, Long, Single or double etc.
The different categories of information/data which a Variant can hold are called as
subtypes.
Below table gives a clear picture of subtypes of data which a Variant can hold or
contain.
Subtype Description
Integer The size is of 2 bytes, Value can be from 0 to 255, The Integer range is from
-32,768 to 32,767.
Long Long is for numbering system, The Integer range is from -2,147,483,648 to
2,147,483,647.
Single Holds small precision, floating point range is from -3.402823E38 to -1.401298E-
45 for negative values and for positive values is from 1.401298E-45 to
3.402823E38.
You can use the conversion functions to convert the data from one subtype to
another subtype which will be discussed in Type Cast lesson.
• Arithmetic Operators.
• Logical Operators.
• Relational or Comparison Operators.
• Concatenation Operator.
VB Script – Arithmetic Operators
- Subtract 5-2 3
* Multiply 5*2 10
^ Exponent 5^2 25
Logical Operators
Logical operators are used to perform logical operations. They are used to
manipulate statements or create logical expressions. The Logical operators
are AND, OR and NOT.
Please find the list of Operators with some examples for easy understanding.
Operator English Meaning Example Result
Not Inverts Value Not False True
For example take this scenario of giving different grades to a student based on the
percentage. For one student you can assign the marks to different variables and
based on the average you can branch out your code and give the grade but imagine
if you have to run it for more that one student then manually you have to go into
the code and change for every student and save and run.
Branching Statements helps you in making the code decide the grade based on the
conditions you give in the code once and ask the user to enter the marks for each
student. Using these branching statements you can branch out your code to
different conditions.
1. If Else
2. If Elseif
3. Switch Case
Out of these the popular branching or conditional statement used is the If Else,
Endif
If [Condition] Then
AAAACode
AAAACode
Else
AAAACode
AAAACode
End If
We will write a script asking the user to enter the average scored and based
conditions given appropriate message is displayed.
If user enters any thing less than 80 say 75 the output displayed will be
What Else if does is that it creates and if statement within an if statement and goes
on and in this manner you can check different conditions in a single if Statement.
If [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Elseif [condition] Then
Code
Else
Code
End If
Now let write a script to see how this works. We will calculate the average for three
subjects and based on the percentage we will display the average and the
appropriate messages.
What happened why did this result came as 100.333333333333 and the first
message will be displayed which is wrong.
Let me explain you what happened so that we will be clear as to what happened
and how to rectify the code.
Now run the script and you will get the right percentage and the required message.
Note: You can also use CINT on the expression instead on inputbox. It will look like
this.
(CINT(mt)+CINT(qtp)+CINT(sql))\3
Let us write a script which can display the resultant value of two integers based on
the selection made. We are computing Addition, Subtraction, Multiplication and
division of the two integers and based on the user selection the operation is
performed.
Case 1
aaamsgbox"The Sumation of "&Var1& " and " &var2& " is: "&Var1 +
Var2
Case 2
aaamsgbox"The difference between "&Var1& " and " &var2& " is:
"&Var1 - Var2
Case 3
aaamsgbox"The product of "&Var1& " and " &var2& " is: "&Var1 *
Var2
Case 4
aaamsgbox"The quotient between "&Var1& " and " &var2& " is: "&Var1
\ Var2
Case Else
aaamsgbox "Invalid entry"
End Select
1. Named Constant
2. Built in Constant
Constant is like a variable but unlike variable the value does not change for the
constant. It is a permanent value stored in the memory.
Named Constant
You will actually assign a integer or a string to a variable but the value assigned to
this variable cannot be changed. It is like a variable but not behave like a variable.
The value does not change and it cannot be used as a variable.
As part of the coding convention it is better to write all the constants in upper case
even though VB Scripting is case insensitive but for easy understanding it is written
and this makes no difference.
Note: The variables are written in lower case. A constant cannot be used
as a variable.
You can create user defined constants using the const statement and can be
created on numeric and string values giving meaningful names.
Syntax
Example
vbApplicationModal Application modal i.e. the current application will not work until the user responds to the message box
vbSystemModal System modal i.e. all applications wont work until the user responds to the message box
Example
The message box displayed will be like this with Yes and No buttons.
Different types of Looping Constructs in VB
Script and its usage in VB Scripting.
Looping constructs allows a user to run a group of statements or piece of code
repeatedly that many times as desired by the user. There are some loops which
repeat statements until the condition become false and others loops which repeat
statements until the condition becomes true. Also there are those loops which
repeat statements for a specific number of times.
There are different kinds of looping construct and based on the requirements we
can use any of this Looping constructs. The are basically two types of looping
constructs FOR and DO. Let’s look at them
DO looping Constructs
1. Do Loop While
2. Do Loop Until
3. Do While Loop
4. Do Until Loop
5. While WEnd Loop
For i = 1 to 10
Msgbox "This loop is repeated "&i& " times"
Next
When you run this script the message box will display “This loop is repeated 1
times” and as you click the number increments till it reaches 10 times and also in
the message the number is incremented and displayed.
In this kind of looping construct we actually change the increment to the desired
number and the increment happens as we desire. To change the default increment
value we use “STEP” along with the For Loop or you can have user defined
increment like i=i+1 etc.
Syntax
Example: We will use the above example and change the increment value as
desired.
For i = 1 to 10 Step 2
Msgbox "This loop is repeated "&i& " times"
Next
Now when you run the script the value is incremented by 2 and the value in the
message box will change and will display as “This loop is repeated 1 times” initially
and then the value changes to 3,5,7,9 and the script terminates because next value
is 11 and is greater than 10.
1. Hope you remember the SELECT CASE statement in which we have looked at a
code where in the user can perform a particular type of operation like addition,
subtraction, multiplication and division. Now using the For loop try to ask the user
how many times the operation should perform. For ex if the user enters 3 then the
code should run for three times.
2. Write a script to print prime numbers based on the user input for the prime
number limit.
3. Write a script to generate the Fibonacci series. Again ask the user for the limit.
4. Write a script to print all the odd numbers till 100. Do not use the STEP
statement.
Syntax
Function [name](arguments)
Code
Code
End Function
Functions in VB Script
Functions helps us to avoid using the same piece of code at different places making
the code bulky instead putting this piece of code in a function and calling it would
solve all the issues and also it maintainable.
1. In built Functions
2. User Defined Functions
In built Functions are those which are already loaded in the VB Script Library while
User Defined Functions are those which the user defines for specific task.
Multiply 3,4
When this script is run the function returns a value of 12. The Variable Multiply is
known as Function Name, byVal is known as Passby, Int1 and Int2 are called as
arguments. The code within the Function name and End Function is called the
Function Body. End Function marks the end of the Function and the whole piece of
code is known as Function Definition.
Generally a function is written to perform a single function i.e. one specific task at a
time. There is a difference between a Function or Procedure and a sub procedure. a
function or procedure returns a value to the calling function while a sub procedure
does not return a value. To put in general
This is a general rule that the Function Definition should happen first and then the
Function Call. Why is it so? The answer is that since we know the requirements and
know how many variables or in this context arguments we use in the function we
should define a function and then write the Function Call because we will use these
arguments in the Function Call. A function can have zero or more arguments.
Function call can happen any where in the script. Function definition can happen
any where in the script but as per coding standards the Function Calls should be at
one place before the Function Definitions and these should also be at one place for
maintainability, ease of understanding.
VB Script searches first the function and then goes and Function Definition and
executes the function.
Procedure Level Variables are also called as Local Variables because they can only
be used in the Procedure or Function. If a variable exists within a function then it
works for that function meaning it is used within the function and the value gets
destroyed once it comes out of the function.
Script Level variables are also called as Global Variables and they can be called
anywhere in the script. These variables can be used even in the Functions but
based on the passby values. These Script Level variables are always declared out
side the procedures.
Then the ‘myfunc’ function is called in line 3 and this function call executes the
function from line 5. Since in the Function definition locally we have assigned x
value as 30 so the msgbox will print 30 and the function is terminated.
Let us look at another example where you can use the name of the function as a
variable name inside the function definition and call that function.
You can write in this way by assigning the function call to a variable and then
passing the variable in the msgbox to print the value. The modified code will be like
this
Let’s take an example and try to understand what happens when a value to an
argument is passed by reference.
x= CINT(Inputbox("Enter a number"))
aaamsgbox "The value outside the function is: "&x
myfunc x
aaamsgbox "The value which is again outside the function is:
"&x
Function myfunc (byref x)
aaax=30
aaamsgbox "The value inside the function is: "&x
End Function
First the x is assigned as 20 and the msgbox in the second line prints 20.
Then the ‘myfunc’ function is called in line 3 and this function call executes the
function from line 5. Since in the Function definition locally we have assigned x
value as 30 so the msgbox will print 30 and the function is terminated.
Then the line 4 which is after the function call ‘myfunc’ is executed and the msgbox
prints x value as 30 because the global variable x value is overwritten with the local
value and prints 30. Since we are using the argument by reference after the
function is called the value of x is 30 and since it is by reference the value of x
permanently becomes 30
Assignment: Convert all the previous written scripts like Fibonacci series,
Prime number Generation, Odd number generation, conversion from
centigrade to Fahrenheit, Addition, Multiplication etc using functions in VB
Script.
It is possible to get different kind of information on Files, Folders and Drives with the
help of FileSystemObject using VB Script.
VB Script can talk to any of the libraries like FileSystemObject, Word, Excel etc. This
is referred to as Component Object Model or COM
1. Standard Class: which are loaded in the Library or which are predefined and we
just need to call them and use them. We cannot make any changes to them.
2. User Defined Class: These are define d by the user for specific tasks.
Let’s take an example of a Class Room. Let’s say that we have two classes named
Male and Female. All the individuals are Objects and they fall into either of the
class. Now each of this Object (individual) has some properties and Methods.
Properties for the above object can be Name, Date of Birth, Height, Weight, Color
and some properties are Read Only which cannot be changed while some others
can be changed. For Example: Date of Birth cannot be changed while height and
weight can be changed or even the name.
Methods for the above Object can be Sleeping, Eating, working, playing etc which
are actions performed by the Object.
In order to call from FileSystemObject (FSO) Library we first need to create and
Object Variable.
An Object Variable is a Variant with sub type which holds an Object and should be
prefixed with a Key word called "SET". To interact with different libraries we need to
create Objects and these Objects are used along with different Methods to perform
different operations.
Here we are creating an object to call a method from the File System Object Library
Set xlapp = CreateObject("Excel.Application")
Here we are creating an object to call a method from the Excel Library
Set IE = CreateObject("InternetExplorer.Application")
Here we are creating an object to call a method from the Internet Explorer Library
Here we are creating an object to call a method from the Quick Test Library
Here we are creating an object to call a method from the Microsoft Word Library
Here we are creating an object to call a method from the Outlook Library
All the above variables are used as a standard convention to understand as to what
the object is doing.
Please look at the following scripts where File System Object is used in VB
Script for various purposes.
1. How to Create a Text File using VB Script? Click Here for the Code
2. How to create multiple Text Files? Click Here for the Code
3. How to create a Folder using VB script? Click Here for the Code
4. How to display File Properties in VB script? Click Here for the Code
VB Script Examples
Next
wbook.SaveAs "F:\Textexcel.xls"
wbook.Close
xlapp.Quit
Once you run this script go to the folder where the excel workbook is created and
open and see how it looks like. The work sheet now contains information in two
columns and in the Cell (1,1) you will find the value as The code of this color is 1 in
black color and in bold and in the cell (1,2) you will find the cell filled with black
color and like wise till row number 56.
Method 1
Method 2
Method 1
Dim arrLines()
i=0
Do Until Fil.AtEndOfStream
aaaRedim Preserve arrLines(i)
aaaarrLines(i) = Fil.ReadLine
aaai = i + 1
Loop
Fil.Close
msgbox str
ReDim arrphonelist(col,row)
For i = 0 to row
aaaFor j = 0 to col
arrubound = ubound(arrphonelist,2)
For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,k)&" "
aaastr = str&arrphonelist(2,k)&vbnewline
Next
Dim arrphonelist()
ReDim arrphonelist(2,row)
For i = 0 to row -1
aaaFor j = 0 to 2
arrubound = ubound(arrphonelist,2)
For k = 0 to arrubound
aaastr = str&arrphonelist(0,k)&" "
aaastr = str&arrphonelist(1,k)&" "
aaastr = str&arrphonelist(2,k)&vbnewline
Next
Dim arrphonelist(2,3)
Arrphonelist(0,1) = "Mark"
Arrphonelist(1,1) = "Robin"
Arrphonelist(2,1) = "9955662233"
Arrphonelist(0,2) = "Peter"
Arrphonelist(1,2) = "Marshal"
Arrphonelist(2,2) = "8080454525"
Arrphonelist(0,3) = "Alex"
Arrphonelist(1,3) = "Blackston"
Arrphonelist(2,3) = "9865653526"
Method 1
objExcel.workbooks.Add()
Const ForReading =1
x=1
Do Until File.AtEndOfStream
Line = File.ReadLine
objExcel.Cells(x,1) = Line
x=x+1
Loop
objFile.Close
Method 2
'Open first text file in read mode and write in excel sheet
Set fil1 = fso.OpenTextFile("F:\TestFolder\Text1.txt",1, False)
X=1
Do Until fil1.AtEndOfStream
strLine = fil1.ReadLine
xlapp.Cells(x,1) = strLine
X=x+1
Loop
wbook.SaveAs "F:\TestFolder\Test.xls"
set wbook=nothing
xlapp.quit
set wsheet = nothing
Set fil = nothing
Set fil1=Nothing
Set fil2 = nothing
'Step 1: Create and object variable to interact with the File system
object
Set fso = CreateObject("Scripting.FileSystemObject")
'Step 3: Return all the files collection from the specified folder
Set fil = Fol.Files
'Print only the text file names from the specified folder
For each f in fil
str = f.name
arr = split(str, ".")
If arr(1) = "txt" then
var = var&Vbnewline&f.name
End If
Next
'Step 1: Create and object variable to interact with the File system
object
Set fso=createobject("Scripting.FileSystemObject")
'Step 2: Point to the folder from which we want to print the file
names
Set fol = fso.GetFolder("F:\YouTube Downloader")
'Step 3: Return all the files collection from the specified folder
Set fil = fol.files
Dim arrcolors(5)
aaaarrcolors(0) = "Blue"
aaaarrcolors(1) = "Green"
aaaarrcolors(2) = "Red"
aaaarrcolors(3) = "White"
aaaarrcolors(4) = "Black"
aaaarrcolors(5) = "Yellow"
arrubound = ubound(arrcolors)
aaamsgbox arrubound
aaaaaaFor i = 0 to arrubound
aaaaaaaaamsgbox arrcolors(i)
aaaaaaNext
To Create a new workbook we need to use this syntax. The syntax to add a
workbook is
To Open an existing workbook we need to use this syntax. The syntax to open an
existing workbook is
To create a worksheet in the workbook we use this syntax and the syntax to create
a worksheet is
Here id can be the sheet id and the index begin with 1. You can also give a string for
the id but should be enclosed in " ".
Variable.SaveAs ()
wbook.SaveAs(("F:\TestFolder\Test.xls")
Every time a workbook is created or opened it should be closed and to close the
workbook we need a Close Method. To close a Work book the syntax is
Variable.Close
wbook.Close
It is a good practice to quit the application once your work is over and to quit the
excel application we need a Quit Method. The syntax is
Object.Quit
Xlapp.Quit
As soon as the application is quit it is required to clear the variables so that it does
not interfere with other scripts. It is important that the worksheet, workbook, excel
application variables should be cleared. To clear the variable used from the memory
we use the Nothing Method. The syntax is
wsheet.cells(rows,columns)
wsheet.cells(1,1)
Write a Script to create two text files and write some lines in the first file and copy
the odd lines of the first file in to the second file.
'Open first text file in read mode and second one in write mode
Set fil1 = fso.OpenTextFile("F:\Text1.txt",1, False)
Set fil2 = fso.OpenTextFile("F:\Text2.txt",2, False)
'Step 1: Create an object variable that interacts with the File System
Object Library
'Step 2; Use the CreateFolder method along with the object to create a
Folder at desired location
Fso.CreateFolder("F:\Test Folder")
'Step 3: Use the GetFolder method to get the newly created file and
store in a variable called s
'Step 4: Use the name method to get the file name and print it along
with the message
Example 2: Asking the user for input to print that many number of files.
Rewrite the code by just adding one line with InputBox function.
'Step 1: Create an object variable that interacts with the File System
Object Library.
'Step 2: Use the CreateTextFile method along with the object to create
a text file at desired location.
Fso.CreateTextFile("F:\Test.txt")
'Step 3: Use the GetFile method to get the newly created file and store
in a variable called s.
Set s = fso.GetFile("F:\Test.txt")
'Step 4: Use the name method to get the file name and print it along
with the message.
Msgbox "The Text Files Created is "&s.name
Here you are asking the user for the choice to perform the operation.
Select Case n
Case 1
aaaaddfunc x,y
Case 2
aaaminusfunc x,y
Case 3
aaamultiply x,y
Case 4
aaaquotient x,y
Case 5
aaaFibonacci var
Case 6
aaaoddfunc var
Case 7
aaaprime var
case 8
aaaconversion cen, fah
Case Else
aaamsgbox "invalid entry"
End Select
Here you are actually defining the functions for different operations to be
performed.
n = CINT(Inputbox("Enter a range"))
f1=0
f2=1
f3=f1+f2
var= f1& ", " &f2
do while f3 < n
var = var& ", "&f3
f1=f2
f2=f3
f3=f1+f2
loop
MsgBox "Fibonacii Series for the limit " &n&" is: " &var
Till the condition is satisfied the inner conditions get executed and stored in the var
variable thus giving out the output as 0,1,1,3,5,8,13,21,34,55 and 89 if we take the
range as 100.
The script for this is given below. What i have done is that before the user to select
the operation before this line we will add few code like an inputbox and a for loop.
The code to be added in the top is like this and at the end of the code add NEXT.
Now we are asking the user how many times the user wants to perform the
operations and taking that value in the variable Varint1 and converting it into
integer. Remember that by default a variant is a string. Then we are passing the
value into the for Loop and incrementing by one value.