Вы находитесь на странице: 1из 58

To Know the Type of File

Set obj=createobject("Scripting.filesystemobject")
Set of=obj.getfile("c:\1.xls")
s=of.type
msgbox s

To Display the Files in a Particular Folder

folderpath="E:\macromedia-8"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderpath)
Set fc = f.Files

For Each f1 in fc
s = s & f1.name &chr(10)
Next

Displaying numbers into Ascending Order By Using Arrays

''''''''''''''''Displaying numbers into Ascending Order By Using


Arrays'''''''''''''''''''''''''''''''''''''''''
a=array(10,20,1,30,2,40,23,50,4)

For j=lbound(a) to ubound(a)


For i=lbound(a) to ubound(a)-1
If a(i)>a(i+1) Then
temp=a(i+1)
a(i+1)=a(i)
a(i)=temp
End If
Next
For i=lbound(a) to ubound(a)
x=x&chr(10)&a(i)
'y=a(i)&chr(10)
Next

msgbox(x)

Swaping two numbers without using 3rd variable

a=inputbox ("Enter the first value:")


b=inputbox( "Enter the second value:")
msgbox "a= "&a&" b= "&b
a=int(a)+int(b)
b=int(a)-int(b)
a=int(a)-int(b)
msgbox "After swap a= "&a&" b= "&b

Write a Mathematical Table in Notepad through the VB Script

'To open notepad and write a mathematical table in that throug QTP and
save in C Drive and close

Set obj=createobject("Scripting.filesystemobject")
Set of=obj.createtextfile("c:\mat.txt")
'set of=obj.opentextfile("c:\mat.txt")
For i=1 to 10
x=5*i
of.writeline"5 * "&i&" = "&x
Next

Comparing Two Files

''''''''''''''''''''''''Compare both the text files and isolate the differences found
in the file1 which are not present in file2''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' in a seperate ouput
file.''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

dim found
set objfso = createobject("scripting.filesystemobject")
set objinputfile2 = objfso.opentextfile ("c:\text2.txt")
set objoutputfile = objfso.createtextfile("c:\output.txt")

do until objinputfile2.atendofstream
found = false
strnextline2 = objinputfile2.readline
set objinputfile1 = objfso.opentextfile ("c:\text1.txt")

do until objinputfile1.atendofstream
strnextline1 = objinputfile1.readline

if (strnextline2 = strnextline1) then


found = true
end if
loop

objinputfile1.close

if (found = false) then


objoutputfile.writeline strnextline2
end if
loop

objinputfile2.close
objoutputfile.close
set objinputfile1 = nothing
set objinputfile2 = nothing
set objoutputfile = nothing

Writing Log Files

Public function generate_result()

starttime=time()
msgbox(nam)
MyArray=split(nam, ":", -1)
For i=0 to ubound(MyArray)
filename=filename+MyArray(i)
Next

Set fso=Createobject("Scripting.FileSystemObject")
Set textfile=fso.createtextfile("c:/result.txt")

textfile.Writeline("Automated Smoke Test Results")


textfile.WriteLine("````````````````````````````")
textfile.WriteBlanklines(3)
textfile.WriteLine("Run on Host : " &
Environment.Value("LocalHostName"))
textfile.WriteBlanklines(1)
textfile.WriteLine("Run on Operating System : " &
Environment.Value("OS"))
textfile.WriteBlanklines(1)
textfile.WriteLine("Run on : "&now)
textfile.WriteBlanklines(1)
endtime=time()
textfile.WriteLine("Test Start Time : " &starttime)
textfile.WriteLine("Test End Time : " & endtime)
textfile.WriteLine("Test Execution Time : " & datediff("s", startime,
endtime)& " Seconds")

End Function

generate_result()

VB Script Procedures

'There are two types of procedures

'1. Function Procedure


'2. Sub Procedure

'Function Procedure-A Function procedure is a series of VBScript


statements enclosed by the Function
'and End Function statements. Function Procedure can able to return
the value.

'Example:

Function demo_add(a,b)

demo_add=a+b

End Function

oVal=demo_add( 2,3)

msgbox oVal 'Returns 5

'In this example demo_add function returns a value to oVal.


'In Function procedures we can use function name to assign a value.

'Sub Procedure-A Sub procedure is a series of VBScript statements


enclosed by the Sub
'and End Sub statements. Sub Procedure cannot return any value.

'Example:

Sub demo_sub(a,b, c)
c=a+b
End sub

demo_sub 2,3,x
msgbox x 'Returns 5

'This example will do the same as what function procedure is doing


above.
'But in sub Procedure we need to use one more parameter to get values
from the sub procedure.
Use of Split Function

''''To display the words in a sentence by spliting with dellimeter''''

str1="arunsingh is a good boy"


var=split(str1," ")
lenarray=ubound(var)
For i=0 to lenarray
str2=var(i)
msgbox str2
Next

Use of RandomNumber Method

set da1=datatable.AddSheet("demo")
set da2=datatable.AddSheet("result")

set pm1=da1.addparameter("name","123")
set pm2= da1.addparameter("age","18")

For i=1 to 10
da1.setcurrentrow(i)
pm1.value="emp"&i
pm2.value=RandomNumber (30,60)
Next

x=da1.getrowcount
set pmr=da2.addparameter("resname","")
set pmg=da2.addparameter("age","")
k=1
For j=1 to x
ag=pm2.valuebyrow(j)

If ag>50 Then
pmr.valuebyrow(k)=pm1.valuebyrow(j)
pmg.valuebyrow(k)=ag
k=k+1
End If

Next

Use of Excel Object Model

''We can do excel operations using excel object model. To find excel
object model in your system follow these steps..

'*********** ********* ********* ********* *


'creating an excel application object
Set Excel=CreateObject( "Excel.Application")
'Adding a sheet in that application
Set ExcelSheet = CreateObject( "Excel.Sheet" )
' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True

'Adding value into sheet


For i=1 to 10
ExcelSheet.ActiveSheet.Cells( i,1).Value = "This is column A, row"&i
Next

' Save the sheet.


ExcelSheet.SaveAs "C:\TEST.xls"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Applicat ion.Quit
' Release the object variable.
Set ExcelSheet = Nothing
'*********** ********* ********* ********* *
''Copy this script in .vbs file and double click on it or paste this script in
QTP and execute it.
''After that go C:\ drive you will find an excel application in the name of
TEST.xls..
''Try to understand this by referring excel object model.. Revert me for
any concerns..
How to set the value for a property

Setting.Add "Tester Name", "Mark Train"

MsgBox Setting("Tester Name")

Use of SetTOProperty

'For example..in first build there is a OK button..and u


'reorded on OK button..

'but in modified build it changed to Yes..and this


'modificatio is only for single build...in this situation u
'need to change that button name OK to Yes

'window("XXXX").winbutton("OK").SetTOProperty "Text","Yes"

To search for something in Google

url="ww.google.com"
systemutil.Run"IEXPLORE",url 'It is to Open a Browser with any
website address

Set gBrowser=Browser("name:=Google.*")
Set gPage=gBrowser.Page("title:=Google.*")
gPage.webedit("name:=q","type:=text","html tag:=INPUT").set "QTP"
gpage.webbutton("name:=Google
Search","index:=0","type:=submit","html tag:=INPUT").click

To Check weather the text contains a particular word or not

var="raju want to marry"


If instr(1,var,"want") Then
msgbox "Exist"
else
msgbox "doesnot Exist"
End If

To check/Uncheck all the checkboxes present on a web page

Systemutil.Run"IExplore","www.yahoomail.com"
wait(10)

Dim obj_DescChk

Set obj_DescChk=Description.Create
obj_DescChk("html tag").value="INPUT"
obj_DescChk("type").value="checkbox"

'obj_DescChk.remove "html tag" '''''''''''''''''''Would delete the html tag


property from the collections
'If obj_DescChk("html tag").value=empty then ''''''''To Know the
property is exists or not in the collection
'obj_DescChk("html tag").value="INPUT" '''''''''''''''''If not then add it to
the collection
'end if

Dim AllChkBoxes, SingleChkBox


Set AllChkBoxes=Browser("title:=Yahoo! Mail: The best web-based
email!").Page("title:=Yahoo! Mail: The best web-based
email!").ChildObjects(obj_DescChk)
msgbox AllChkBoxes.count
For i=0 to AllChkBoxes.count-1
AllChkBoxes(i).set "ON"
Next

To retrive data from datatable which is in 3rd row and 4th column

'in Action1 sheet change the names of A,B,C,D columns with A,B,C,D
respectively.
'And type the values in D column
datatable.SetCurrentRow(3)
answer=datatable(4,2)'.Value(4,2) '4th column in 2nd Sheet
msgbox answer
'Run the program

'-------------------------------------
'To retrive value from 3rd row 4th column from external excel sheet

datatable.Importsheet "c:/1.xls",1,1
datatable.SetCurrentRow(3)
val=datatable.Value(4,1)'4th column 1st sheet
msgbox "The Value is "&val

How to paste a image in Word Document

Set objWord = CreateObject( "Word.Application")


objWord.Visible = True
Set objDoc = objWord.Documents. Add()
Set objSelection = objWord.Selection

Set objShape = objDoc.Shapes


objShape.AddPicture ("c:\image010.jpg")

To Know the No of Items in the Web Page

url="http://my.naukri.com/manager/createacc2.php?othersrcp=5421&
wExp=N"
'url="www.gmail.com"
'url="www.yahoomail.com"

If Browser("index:=0").Exist(1) then' If Browser is already opened


a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate(url)
Browser("hwnd:=" & a).Sync
wait(2)
Else' If Browser is not opened
SystemUtil.Run"IEXPLORE.exe"
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate(url)
Browser("hwnd:=" & a).Sync
wait(2)
End If

Set Editobj=Description.Create'For WebEdits


Editobj("html tag").value="INPUT"
Editobj("kind").value="singleline"

Set Butobj = Description.Create'For Buttons


Butobj("html tag").value = "INPUT"
Butobj("type").value="submit"

Set Listobj=Description.Create'For Web Lists


Listobj("html tag").value="SELECT"

Set Linkobj=Description.Create'For Link


Linkobj("html tag").value="A"

Set Checkboxobj=Description.Create'For Checkboxes


Checkboxobj("html tag").value="INPUT"
Checkboxobj("type").value="checkbox"

Set Radioobj=Description.Create'For Radio Buttons


Radioobj("html tag").value="INPUT"
Radioobj("html id").value="ctctype_i"

Set Edits = browser("hwnd:="


&a).Page("title:=.*").ChildObjects(Editobj)
Set Buttons = browser("hwnd:="
&a).Page("title:=.*").ChildObjects(Butobj)
Set Lists = browser("hwnd:=" &a).Page("title:=.*").ChildObjects(Listobj)
Set Links = browser("hwnd:="
&a).Page("title:=.*").ChildObjects(Linkobj)
Set Checks = browser("hwnd:="
&a).Page("title:=.*").ChildObjects(Checkboxobj)
Set Radios = browser("hwnd:="
&a).Page("title:=.*").ChildObjects(Radioobj)

msgbox "Total EditBoxes are : "&Edits.count


msgbox "Total Button are : "&Buttons.count
msgbox "Total Lists are : "&Lists.count
msgbox "Total Links are : "&Links.count
msgbox "Total checkBoxes are : "&Checks.count
msgbox "Total RadioButtons are : "&Radios.count

To Insert a Value in a Exce l Sheet

''''''''''''''''''''To Insert a Value in a Exce l Sheet'''''''''''''''''''''''''

Set xl=createobject("Excel.Application")
Set x=xl.workbooks.open("c:/arun.xls")
Set y=xl.activeworkbook.worksheets("sheet1")
xl.cells(1,1)="arun"

To get the only numbers from the flat file and store in a datatable

'bombay 100 hyderabad jkjk '


'djkhkk ksljk 88 asdk '
'dkjsajl kskj kjhsjk 88 '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''To get the only numbers from the flat file
and store in a datatable''''''''''''''''''''''''''''''''''''
set fso=createobject("scripting.filesystemobject")
set oText=fso.opentextfile("c:/demo.txt",1)
datatable.getsheet(1).addparameter"Numbers",""
row=1
While not oText.atendofline
text=oText.readline
n=split(text," ")
for i=lbound(n) to ubound(n)
If isnumeric(n(i)) then
datatable.setcurrentrow(row)
datatable(1,1)=n(i) '''''''''''''''datatable(ColumnNo,SheetNo)
row=row+1
end if
Next
wend

To Display the Files in a Particular Folder

'''''''''''''''''''To Display the Files in a Particular Folder'''''''''''''''''''''''''''''''''''

folderpath="E:\macromedia-8"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderpath)
Set fc = f.Files

For Each f1 in fc
s = s & f1.name &chr(10)
Next

To count the no of links and button in a web page

'''''''''''''''''''''''''Open A Google Page and Count the No Of Links and Buttons


in that page'''''''''''''''''''''''''''''''''''
''
''
''
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
If Browser("index:=0").Exist(1) then' If Browser is already opened
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate("http://www.google.com")
Browser("hwnd:=" & a).Sync
wait(2)
Else' If Browser is not opened
SystemUtil.Run"IEXPLORE.exe"
a = Browser("index:=0").GetROProperty("hwnd")
Browser("hwnd:=" & a).Navigate("http://www.google.com")
Browser("hwnd:=" & a).Sync
wait(2)
End If

Set Butobj = Description.Create()'For Button


Butobj("html tag").value = "INPUT"'For Button
Butobj("type").value="submit"'For Button

Set Linkobj=Description.Create()'For Link


Linkobj("html tag").value="A"'For Link

Set Buttons = browser("hwnd:="


&a).Page("title:=.*").ChildObjects(Butobj)
Set Links = browser("hwnd:="
&a).Page("title:=.*").ChildObjects(Linkobj)

msgbox "Total Button are : "&Buttons.count


msgbox "Total Links are : "&Links.count

To copy contents of one file to another file

'To copy contents of one file to another file

Set fso=createobject("scripting.filesystemobject")
Set fname=fso.opentextfile("C:/mtable.txt",1)
Set fname1=fso.createtextfile("C:/duptable1.txt")
Do while not fname.atendofstream
n=fname.readline
fname1.writeline n
Loop
To Color the column in a excel sheet

'""""To Color the column in a excel sheet.""""""""""""""''''

Set xlApp=Createobject("Excel.Application")
set xlWorkBook=xlApp.workbooks.add
set xlWorkSheet=xlWorkbook.worksheets.add
xlWorkSheet.Range("A1:B10").interior.colorindex = 34 'Change the
color of the cells
xlWorkSheet.Range("A1:A10").value="text" 'Will set values of all 10
rows to "text"
xlWorkSheet.Cells(1,1).value="Text" 'Will set the value of first row and
first col

rowsCount=xlWorkSheet.Evaluate("COUNTA(A:A)") 'Will count the # of


rows which have non blank value in the column A
colsCount=xlWorkSheet.Evaluate("COUNTA(1:1)") 'Will count the # of
non blank columns in 1st row

xlWorkbook.SaveAs "C:\Test.xls"
xlWorkBook.Close
Set xlWorkSheet=Nothing
Set xlWorkBook=Nothing
set xlApp=Nothing

To know the no of list items in the web page

''''''''''''''''''''To know the no of list items in the web page'''''''''''''''''''''''''''''''''

url="http://corp.naukri.com/mynaukri/mn_newsmartsearch.php?xz=2
_0_5&id="
Systemutil.Run "Iexplore.exe",url
set oDesc= Browser("name:=Mynaukri : naukri.com - India's No.1 Job
Site")
itemcount=oDesc.WebList("name:=qe").GetROProperty("items count")
msgbox "Number of Items in Experience List= "& itemcount
itemcount=oDesc.WebList("name:=qm").GetROProperty("items count")
msgbox "Number of Items in Minimum Salary List= "&itemcount

Replace all text with a new text in a text file

Set oDesc=createobject("scripting.filesystemobject")
Set oFile=oDesc.opentextfile("c:/demo.txt",2,true)'''''1-Reading 2-
Writing 3-Appending
oFile.write "Hello World"

Open Dialog box from Tool Menu of the MS Word Application

'This program will open a word pad and enter some text (impossibel)
and checks the spelling and grammar in that text
'This program will open a word and opens a spelling and grammar dialog
box for tools menu

Const wdDialogToolsSpellingAndGrammar = 828


Const wdDoNotSaveChanges = 0

Uncorrected = "impossibel"
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Add
Word.Selection.Text = Uncorrected
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show
If Len(Word.Selection.Text) <> 1 Then
Corrected = Word.Selection.Text
Else
Corrected = Uncorrected
End If
Doc.Close wdDoNotSaveChanges
Word.Quit

Multiple Screen shots at runtime


''''''''''''''''''''''''''''''''To create multiple screeen shots at
runtime''''''''''''''''''''''''''''''''''''''

Systemutil.run"C:\Program Files\Mercury Interactive\QuickTest


Professional\samples\flight\app\flight4a.exe"
Set Dlg= Dialog("text:=Login")
Set wnd=Window("text:=Flight Reservation")
Set oDlg=wnd.Dialog("text:=Open Order")

Dlg.WinEdit("attached text:=Agent Name:").set "rajaputra"


Dlg.WinEdit("attached text:=Password:").setsecure"mercury"
Dlg.WinButton("text:=OK").click

wait(7)
For i=1 to
wnd.Activate
wnd.WinButton("window id:=5").click
oDlg.WinCheckBox("text:=&Order No.").set "ON"
oDlg.WinEdit("window id:=1016").set "55"
oDlg.WinButton("text:=OK").click

if(oDlg.Dialog("text:=Flight Reservations").Exist) then


oDlg.Dialog("text:=Flight
Reservations").CaptureBitmap"c:\snapshot"&i&".bmp"
oDlg.Dialog("text:=Flight Reservations").WinButton("text:=OK").click
oDlg.WinButton("text:=Cancel").click
end if
Next
wnd.Close

DP from Logging in - Open a Order and Closing the Flight


Reservation Application

''''''''''''''' Discriptive Program for starting from Logging in - Opening a


order and closing the Flight Reservation Application'''''''''''''
''''''''''''''Importing the Excel sheet into datatable and Exporting the
Datatable into Excel file''''''''''''''''''''''''''''''''''''''''

systemutil.Run "C:\Program Files\Mercury Interactive\QuickTest


Professional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").Activate
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").set
"rajaputra"
Dialog("text:=Login").WinEdit("attached text:=Password:").set
"mercury"
Dialog("text:=Login").WinButton("text:=OK").click
wait(5)
Window("text:=Flight Reservation").Activate
datatable.Importsheet "c:/orders.xls",1,1' 1st sheet will be imported into
the 1st sheet in runtime datatable
rowcount=datatable.GetRowCount
'msgbox rowcount
For i=1 to rowcount
Window("text:=Flight Reservation").WinButton("window id:=5").click
Dialog("text:=Open Order").Activate
Dialog("text:=Open Order").WinCheckBox("text:=&Order No.").set
"ON"
datatable.SetCurrentRow(i)
n=datatable(1,1) '1st column 1st sheet
Dialog("text:=Open Order").WinEdit("window id:=1016").set n
Dialog("text:=Open Order").WinButton("text:=OK").click
If(window("text:=Flight Reservation").Dialog("text:=Open
Order").Dialog("text:=Flight Reservations").exist)then
window("text:=Flight Reservation").Dialog("text:=Open
Order").Dialog("text:=Flight
Reservations").WinButton("text:=OK").click
window("text:=Flight Reservation").Dialog("text:=Open
Order").WinButton("text:=Cancel").click
datatable(2,1)="Not Exist"'2nd column 1st sheet
Else
datatable(2,1)="Exist" '2nd column 1st sheet
end if
Next
DataTable.Exportsheet"C:\flight.xls",1'1st sheet of the runtime datatable
will be exported at last sheet in flight.xls
Window("text:=Flight Reservation").Close

Importing Data from Flat File using Split function

'''''''''''''''''Importing Data From Flat File using split''''''''''''''''''''''''''''


''Source.txt file is having following data
''Arunsingh,40000,KiranKumar,35000,Chandra,50000
''Test Engineer,Developer,Project Leader

Set fso=createobject("scripting.filesystemobject")
Set z=fso.opentextfile("c:\source.txt",1)
l=1
While not z.atendofline
i=1
k=1
count=1
parname=inputbox("Enter Name of The Parameter "&l) '''''Enter the
requiered parameter names
datatable.GetSheet(1).addparameter parname,""
n=z.readline
a=split(n,",")
For j=lbound(a) to ubound(a)

If isnumeric(a(j)) Then
If count=1 Then
datatable.GetSheet(1).addparameter "Salary",""
count=count+1
end if
datatable.SetCurrentRow(k)
m=l +1
datatable(m,1)=a(j)
k=k+1
else
datatable.SetCurrentRow(i)
datatable(l,1)=a(j)
i=i+1
end if
Next
l=m
l=l+1
Wend

Fixed VS Dynamic Arrays

'Using Fixed arrays

Dim x(2)

x(0)="how"
x(1)="are"
x(2)="you"

for i=lbound(x) to ubound (x)


msgbox x(i)
Next

'Here we cann't store more than 3 elements. Because this is a fixed


length array..

'Using Dynamic Arrays

Dim x()

Redim preserve x(2)

x(0)="how"
x(1)="are"
x(2)="you"
Redim preserve x(3)
x(3)=123

'Here 'x' is a dynamic array and by redeclaring x it can able to store more
values into it.

Displaying Numbers into Ascending Order

''''''''''''''''Displaying numbers into Ascending Order By Using


Arrays'''''''''''''''''''''''''''''''''''''''''
a=array(10,20,1,30,2,40,23,50,4)

For j=lbound(a) to ubound(a)


For i=lbound(a) to ubound(a)-1
If a(i)>a(i+1) Then
temp=a(i+1)
a(i+1)=a(i)
a(i)=temp
End If
Next
Next

For i=lbound(a) to ubound(a)


x=x&chr(10)&a(i)
Next

msgbox(x)

Capture the Screen shot during runtime

''''''''''''''''''''''Capture the Screen Shot when Error Is


Occured'''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''Using Objects'''''''''''''''''''''''''''''''''''''''''''''''''
Systemutil.run"C:\Program Files\Mercury Interactive\QuickTest
Professional\samples\flight\app\flight4a.exe"
Set Dlg= Dialog("text:=Login")
Set wnd=Window("text:=Flight Reservation")
Set oDlg=wnd.Dialog("text:=Open Order")

Dlg.WinEdit("attached text:=Agent Name:").set "rajaputra"


Dlg.WinEdit("attached text:=Password:").setsecure"mercury"
Dlg.WinButton("text:=OK").click

wait(7)

wnd.Activate
wnd.WinButton("window id:=5").click
oDlg.WinCheckBox("text:=&Order No.").set "ON"
oDlg.WinEdit("window id:=1016").set "55"
oDlg.WinButton("text:=OK").click

if(oDlg.Dialog("text:=Flight Reservations").Exist) then


oDlg.Dialog("text:=Flight
Reservations").CaptureBitmap"c:\snapshot1.bmp"
oDlg.Dialog("text:=Flight Reservations").WinButton("text:=OK").click
oDlg.WinButton("text:=Cancel").click
end if

wnd.Close

Export Datatable into Text File

Pre Requisite - abc.xls with one sheet with some values in first column

textfile="c:\demo.txt"
Set fso=createobject("scripting.filesystemobject")
Set f=fso.createtextfile(textfile,2)

datatable.Import("C:\abc.xls")
set dg=datatable.GetSheet(1)

x=dg.getparametercount
rc=dg.getrowcount

For i=1 to x
n=dg.getparameter(i).name ' Gives the First coulmn name
Set pmg=dg.getparameter(n)
f.writeline(n)
For j=1 to rc
f.writeline(pmg.valuebyrow(j))
next
Next

Use of Flat File

''''''''Pre requisite---Open A Note Pad and enter some order nos 1 by 1,


and Save it as flat.txt in c:\\'''''''''''''''''''''''''

Set z=createobject("scripting.filesystemobject")
Set f=z.opentextfile("c:\flat.txt",1)
While f.atendofline<>true
n=f.readline
Window("Flight Reservation").WinMenu("Menu").Select "File;Open
Order..."
Window("Flight Reservation").Dialog("Open
Order").WinCheckBox("Order No.").Set "ON"
Window("Flight Reservation").Dialog("Open
Order").WinEdit("Edit").Set n
Window("Flight Reservation").Dialog("Open
Order").WinButton("OK").Click
Wend

Creating Constants

Constants-A constant is a meaningful name that takes the place of a


number or string and never changes.
The difference between variable and constant is we can change the
variable value in run time
but for constants its not possible.

Creating constants

const str="RAJAPUTRA"

here str is a constant and the value will never change.

We have public and Private constants. By default all are public. If you
want specify the type then

Public const str="RAJAPUTRA"


or
Private const str="RAJAPUTRA"

Copying Files and Folders

Set fso=createobject("scripting.filesystemobject")
fso.copyfile"C:/SourceFileName.ext","c:/DestinationFile Name.ext" 'For
copying a Files
fso.copyfolder "C:/SourceFolderName","C:/DestinationFolderName" '
For copying a Folders

Copy the Data from One Sheet to Another Sheet

'''Let assume we have a excel file called abc.xls in C drive.


'''In abc.xls we have one sheet with some values.
'''We need to copy first sheet values into second sheet

datatable.Import("c:\abc.xls")
Set src=datatable.GetSheet(1) 'Source Sheet
Set dsc=datatable.GetSheet(2) 'Destination Sheet

pc=src.getparametercount 'Get the Source sheet column count


rc=src.getrowcount 'Get the Source sheet row count
For i=1 to pc
n=src.getparameter(i).name ' Get the Source sheet column name
'msgbox n
Set pmg=src.getparameter(n)
Set pm=dsc.addparameter(n,"")

For j=1 to rc
pm.valuebyrow(j)=pmg.valuebyrow(j)
next
Next

By Value Vs By Reference

Types of arguments in procedures

1. ByVal
2. ByRef

ByVal:

Indicates that the argument is passed by value.

ByRef :
Indicates that the argument is passed by reference.

By default all arguments are 'ByRef'.

Syntax -

Function demo_add(a,b)

demo_add=a+b

End Function
Here a,b are the arguments. By default these are 'ByRef'.

In simple words ByRef Means the value which is assigned to the variable
with in the function is permanent and we can use that value out side of
that function also.

ByVal means the value which is assigned to the variable with in the
function is temporary
and we can use that value only with in that function.

Example:

Function demo_parameters( byref x,byval y)


x=20
y=50
demo_parameters= x+y
End Function

a=10
b=20
msgbox demo_parameters( a,b)
msgbox a
msgbox b

In the above function x and y are the arguments, declared as byref and
byval.
With in that function i assigned values to x and y.

Outside of the function i assigned values to two variables and passing


those variables in to the function.
'a' is passing reference to x and b is passing value to y.

With in that function i am changing the value for x. This value is


permanent for 'a'. Because 'a' is passed as 'ByRef'.
But the value of 'b' will not be changed because it is passed as 'ByVal'.

To display the message box in two lines

msgbox "FIRSTLINE"&vbcrlf&"SECONDLINE"

To open a word doc,type something and save the doc and close

set WordObj = CreateObject("Word.Application")


WordObj.visible = true
Set WordDoc = WordObj.Documents.Add
WordDoc.Range.InsertBefore "Hi Good Morning!"
WordDoc.SaveAs "C:\Greetings.doc"
WordObj.quit
Set WordObj = nothing

Defference between Import and ImportSheet

Import method will imports the specified Excel file to the run time
datatable.
Ex: Datatable.Import ("C:\sample.xls")

ImportSheet method will imports a specified sheet of a specified file to a


specified sheet in the datatable.
Ex: Datatable.ImportSheet "c:\sample.xls", SourceSheetName(or
Number), DestinationSheetName(or Number)

If excel file has 7 sheets, if we use import method, then all the 7 Sheets
are imported into the runtime datatabe?
The Answer is No. Only the first 2 sheets will be imported into the
runtime datatable.
Not all the sheets.
why because, By default datatable will have 2 sheets (Global/Local)
If you add an action in the QTP then only, a new sheet will be added in to
the datatable.
How to compare the list box items with another

Here i am giving the script to compare the list box items with another -
To run this script you have to add all the objects into the object
repository
(Find the link in this blog "how to add objects into the object
repository")

Window("Flight Reservation").activate
SeltItem = window("Flight Reservation").winComboBox("Fly
From:").GerROProperty("text")
msgbox SelItem
'It displays the selected item in the list
ListItem = Window("Flight Reservation").WinComboBox("Fly
To:").GetContent
msgbox ListItem
'It displays all the items in the list box
Itemcount = window("Flight Reservation").WinComboBox("Fly
To:").GerItemsCount
msgbox Itemcount
'It displays no of items in the list box
For i=0 to Itemcount-1
a=window("Flight Reservation").wincombobox("Flt To:").GetItem(i)
If SelItem=a Then
msgbox "Items Are Matching"
else
msgbox "Items Are Not Matching"
End If
Next

Script for Orkut Login

url = "www.orkut.com"
Systemutil.Run "IExplore", url
'It will open a Browser with any website address
Browser("name:=orkut - login").WebEdit("name:=Email").set
"rajaputra"
Browser("name:=orkut - login").WebEdit("name:= Passwd").setSecure
"47525d8be4926ea2f6e96b9a3f7472b6ae38"
Browser("name:=orkut - login").WebButton("name:=Sigh in").Click
Browser("name:=orkut - login").Link("name:=Logout").Click
Browser("name:=orkut - login").Close

Import and Export Methods

Here i am giving the script for Importing data from data table and
exporting the data table into Excel File.

SystemUtil.Run "C:\ProgramFiles\Mercury Interactive\QuickTest


Professional\samples\flight\app\flight4a.exe"

Dialog("text:= Login").Activate
Dialog("text: = Login").WinEdit("Attached text:=Agent Name").set
"rajaputra"
Dialog("text: = Login").WinEdit("Attached text:=Password").set
"mercury"
Dialog("text:=Login").WinButton("text:=OK").Click
Window("text:=Flight Reservation").Activate
datatable.importSheet "C:\example.xls",1,1
rowcount=datatable.GetRowCount
For i=1 to rowcount
Window("text:=Flight Reservation").WinButton("window id:=5").Click
Dialog("text:=Open Order").Activate
Dialog("text:=Open Order").WinCheckBox("text:=&Order No.").set
"ON"
datatable.SetCurrentRow(i)
n=datatable(1,1)
Dialog("text:=Open Order").WinEdit("window id:=1016").set n
Dialog("text:=Open Order").WinButton("text:=OK").Click
If(window("text:=Flight Reservation").Dialog("text:=Open
Order").Dialog("text:=Flight Reservation").exist)then
window("text:=Flight Reservation").Dialog("text:=Open
Order").WinButton("text:=Cancel").Click
datatable(2,1)="Not Exist"
Else
datatable(2,1)="Exist"
End If
Next
Datatable.Export ("C:\flights.xls")
window("text:=Flight Reservation").Close

Before running this script, in "example.xls" you have to put two


columns.
one is OrderNo and one is Result.
In OrderNo you can enter any valid or invalid OrderNo's and Result you
can leave as it is.
We will out put the data into Results.

What is Input Parameters and OutPut Parameters

Input parameter allows you to run a test using different set of data input
values.
When you use a datatable parameter, you must instruct QuickTest on
where the input data will come from.

An output parameter is a value which comes back from the application


under test. When you run the test QuickTest retrieves the current value
of the property and enters it in the run-time datatable as an output
value.

You can subsequently use this output value as a input value in your test.
We call this data correlation. This enables you to use data retrieved
during other parts of test.

How to run the batch file through Script


I have taken 3 tests as a example for doing batch run. They are

1. Display -It will display a message in a word doc.


2. DisplayDate - It will display a date and time in a Notepad
3. Multiplication - It will display a mathematical table in Notepad

I converted them in respective funcitons and saved in notepad as a .vbs


file.
(in C:\VBLibraryFiles\)
And i wrote a VBS Finction that is called above 3 functions and saved as a
callAll.vbs
(in C:\VBLibraryFiles\)
Before running the test I loaded all files into resource tab

callAll() 'Here i am just calling callAll function which is defined in


callAll.vbs file

**********************

Display.vbs -

public funciton display()

set WordObj = CreateObject("Word.Application")


WordObj.visible = true
Set wordDoc = WordObj.Documents.Add
WordDoc.Range.InsertBefore "Hi Good Morning"
WordDoc.SaveAs "C:\Greetings.doc"
WordDoc.quit
Set wordObj = Nothing

End Function

***********************

DisplayDate.Vbs -
Public Function displayDate()

Set fso = createObject("Scripting.filesystemObject")


Set fptr = fso.createTextfile("C:\Sample.txt")
a = FormatDateTime(Date,1)
fptr.writeLine a

End Function

*******************************

Multiplication.Vbs -

Public Function multiplication()

Set obj = createObject("Scripting.filesystemObject")


Set of = obj.createTextFile("C:\mat.txt")
For i=1 to 10
x=5*1
of.writeLine "5 * "&i&" = "&x
Next

End Function

*****************************

CallAll.Vbs -

Public Function callAll()

display()
msgbox "Test 1 is pass"
displayDate()
msgbox "Test 2 is pass"
multiplication()
msgbox "Test 3 is pass"

End Function

How to copy the file from one location to another location

dim filesys
Set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("C:\sourcefolder\anyfile.ext") then
filesys.CopyFile "C:\sourcefolder\anyfile.ext", C:\destinationfolder\"
End If

How to get the Count of each file in a particual folder

Set fso = CreateObject("Scripting.FileSystemObject")


Set fold = fso.getFolder("D:\testingfiles")
Set fc = fold.files

word=0
xls=0
txt=0

datatable.getSheet(1).addParameter "Word",""
datatable.getSheet(1).addParameter "Excel",""
datatable.getSheet(1).addParameter "text",""
datatable.getSheet(1).addParameter "Total Files",""

For each f in fold.files

if lcase(right(f.name,4)) = ".doc" then


word=word+1
end if

if lcase(right(f.name,4))= ".xls" then


xls=xls+1
end if
if lcase(right(f.name,4))= ".txt" then
txt=txt+1
end if
next

datatable(1,1)=word
datatable(2,1)=xls
datatable(3,1)=txt
datatable(4,1)=fc.count

Is VB Script Supports OOPS Concept . . .

My answer for this is No but Yes.


To supports the OOPs concept, the script needs to be satisfy the OOPs
principles.

OOPS Principles -
1.Encapsulation
2.Inheritance
3.Polymorphism

Lets write a script to satisfy each principle -

Encapsulation - The wrapping of data and function into a single unit


(Called class) is known as Encapsulation.

Example -

Class Maths

Function add(a,b)
MsgBox "Sum = "&a+b
End Function
End Class

Set Mat=New Maths


res=Mat.add (2,3)

'*****************************************************************************
*******

Inheritance - It is the process by which object of one class acquire the


properties of object of another class.

'Example -

Class Outer
Function test()
Set inn= New Inner
inn.display
End Function

End Class

Class Inner
Function display()
MsgBox "This is inner class"
End Function
End Class

Set out=New Outer


out.test()

'*****************************************************************************
*******

'Polymorphism - Polymorphism means the ability to take more than one


form/methods
Example -

Dim idno, name, marks


Class Student

Function SetData()
idno="10"
name="arun"
marks="300"
End Function

Function getData()
MsgBox "Idno "&idno
MsgBox "Name "&name
MsgBox "Marks "&marks
End Function

End Class

Class Student2

Function SetData(a,s,m)
idno=a
name=s
marks=m
End Function

End Class

Set Std1=New Student


std1.SetData()
std1.getData()
Set std2=New Student2
std2.SetData "12","Singh","400"
std1.getData()
I am trying to say Yes, it supports OOPS concept. But if any body is
having any questions or my assumption is wrong then please post here
as a comments.

*****************************************************************************
********

How to Click on Dinamic Links

Here is the script to click on the dynamic Links in table. Even though if any link are
dynamic we can get control on the links by using index.

'*******************************************************************
Set TblObj=Browser( BrowserProp) .Page(PageProp) .WebTable( TableProp)

r_Count=TblObj. RowCount

For r=1 to r_Count


c_Count=TblObj. ColumnCount( r)

For c=1 to c_Count

chItems_Count= TblObj.ChildItem Count(r,c, "Link")

For ItemIndex=0 to chItems_Count- 1

Set ch_Item=TblObj. ChildItem( r,c,"Link" ,ItemIndex)


Print ch_Item.object. title
ch_Item.click
' Specify the required operations after clicking on link
' Make sure that again you should navigate to the same page to get other links tooltip
'Or to click on other Links
Next

Next
Next
'**********************************************************************

How To Run QTP Scripts at Scheduled Time?

I have gathered this information from learnqtp.com by Ankur.

There can be situations when you need to schedule your QTP scripts so
that they can run when you are not present in front of you PC. I will show
you a demo below -
1) Create a .vbs fild to launch QTP with requiresd settings, add-ins etc.\\
Here is a sample vbs code

Set App = CreateObject("QuickTest.Application")

App.Launch

App.Visible = True

App.WindowState = "Maximized"

App.ActivateView "ExpertView"

App.open "C:\Program Files\Mercury Interactive

\QuickTest Professional\Tests\Test1", False

'Opens the test in editable mode

2) OK, for the first timers. Create a sample QTP test and save it as Test1
at the location above. Copy the code into notepad and name the file as
testing.vbs

3) Now we will automate the opening of vbs file through windows


scheduyler. Go to Start > Control Panel > Schedule Tasks > Click Add
Schedule Tasks Click Next on the Screen
4) Click Browse and select the .vbs file you just created. You will ge this
screen.

5) Give a name to the task and select the frequence for performing the
given tasks. For this demo we will select "One time only"

6) Select Start Time and Start Date. For this demo, select Start Time as
current time+5 mins and Start date as today date.
7) Next Screen Enter "UserNAme", "Password" and "Confirm Password"

8) Click on Finish, you're done.

Environment Variables

Environment variables in QTP are like global variables in other programming


languages which can be accessed through any part of the script. The values of
these variables remains same irrespective of the number of iterations (unless you
change them through scripting). These variables can prove to be very useful
when you want a variable to be shared across various reusable actions.

There are two types of environment variables:

1. Built-In: These are the internal variables that are provided by QTP.
Among others they can provide you valuable information like the path of
the folder where test is located, the path of the results folder, the name of
the action iteration or the OS version. So, how can we access the built in
environment variable? Its simple, just have a look at screenshot. So if you
want to know the OSVersion of the operating system where your test is
running. You can simply type in
2. Environment.Value(OSVersion)
3. User-Defined: These can be further defined into two types.
o User defined Internal
These are the variables that we define within the test.
These variables are saved with the test and are accessible only
within the test in which they were defined.
So how can we define and use them?
To define them: Environment.Value(name)= Rajaputra
To call them: msgbox Environment.Value(name)
o User defined External
These are the variables that we predefine in the active
external environment variables file.
These can be created using a list of variable-value pairs in an
external file in .xml format. This is a topic of a separate post
that we will discuss later.

We can use environment variables in a number of ways:

1) When you want a global variable that is needed throughout the test run
(across all your reusable actions).

2) When you see that one reusable action in a script is dependent on the
others. You might want to use them

3) When you need to reference the current test directory irrespective of


the location where it is stored.

Environment Variables

Environment variables in QTP are like global variables in other programming


languages which can be accessed through any part of the script. The values of these
variables remains same irrespective of the number of iterations (unless you change
them through scripting). These variables can prove to be very useful when you want a
variable to be shared across various reusable actions.
There are two types of environment variables:

1. Built-In: These are the internal variables that are provided by QTP. Among
others they can provide you valuable information like the path of the folder
where test is located, the path of the results folder, the name of the action
iteration or the OS version. So, how can we access the built in environment
variable? Its simple, just have a look at screenshot. So if you want to know the
OSVersion of the operating system where your test is running. You can simply
type in Environment.Value(OSVersion)
2. User-Defined: These can be further defined into two types.
o User defined Internal
These are the variables that we define within the test.
These variables are saved with the test and are accessible only
within the test in which they were defined.
So how can we define and use them?
To define them: Environment.Value(name)= Rajaputra
To call them: msgbox Environment.Value(name)

o User defined External


These are the variables that we predefine in the active external
environment variables file.
These can be created using a list of variable-value pairs in an
external file in .xml format. This is a topic of a separate post that
we will discuss later.

3. We can use environment variables in a number of ways:


1) When you want a global variable that is needed throughout the test run
(across all your reusable actions).
2) When you see that one reusable action in a script is dependent on the others.
You might want to use them
3) When you need to reference the current test directory irrespective of the
location where it is stored.

Excel Automation

Here are the few functions to automate the excel application.


'To Open a Microsoft Excel application with default new work book

Function CreateExcel()
Dim excelSheet
Set ExcelApp = CreateObject("Excel.Application") 'Create a new Microsoft Excel
object
ExcelApp.Workbooks.Add
ExcelApp.Visible = True
Set CreateExcel = ExcelApp
End Function

'To Close the given Microsoft Excel document

Sub CloseExcel(ExcelApp)
Set excelSheet = ExcelApp.ActiveSheet
Set excelBook = ExcelApp.ActiveWorkbook
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.CreateFolder "C:\Temp"
fso.DeleteFile "C:\Temp\ExcelExamples.xls"
excelBook.SaveAs "C:\Temp\ExcelExamples.xls"
ExcelApp.Quit
Set ExcelApp = Nothing
Set fso = Nothing
Err = 0
On Error GoTo 0
End Sub

'The SaveWorkbook method saves a workbook according to the workbook identifier.


'The method overwrites the previously saved file in the given path.
'excelApp - a reference to the Microsoft Excel application
'workbookIdentifier - The name or number of the requested workbook
'path - The location to which the workbook should be saved
'Returns "OK" on success and "Bad Workbook Identifier" on failure

Function SaveWorkbook(ExcelApp, workbookIdentifier, path) 'As String


Dim workbook 'As Excel.workbook
On Error Resume Next
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
On Error GoTo 0
If Not workbook Is Nothing Then
Set fso = CreateObject("Scripting.FileSystemObject")
'If the path has no file extension then add the 'xls' extension
If InStr(path, ".") = 0 Then
path = path & ".xls"
End If
On Error Resume Next
fso.DeleteFile path
Set fso = Nothing
Err = 0
On Error GoTo 0
workbook.SaveAs path
SaveWorkbook = "OK"
Else
SaveWorkbook = "Bad Workbook Identifier"
End If
End Function

'The SetCellValue method sets the given 'value' in the cell which is identified by
'its row, column, and parent Microsoft Excel sheet
'excelSheet - The Microsoft Excel sheet that is the parent of the requested cell
'row - the cell's row in the excelSheet
'column - the cell's column in the excelSheet
'value - the value to be set in the cell

Sub SetCellValue(excelSheet, row, column, value)


On Error Resume Next
excelSheet.Cells(row, column) = value
On Error GoTo 0
End Sub

'The GetCellValue returns the cell's value according to its row, column, and sheet
'excelSheet - The Microsoft Excel sheet in which the cell exists
'row - The cell's row
'column - The cell's column
'return 0 if the cell cannot be found

Function GetCellValue(excelSheet, row, column)


value = 0
Err = 0
On Error Resume Next
tempValue = excelSheet.Cells(row, column)
If Err = 0 Then
value = tempValue
Err = 0
End If
On Error GoTo 0
GetCellValue = value
End Function

'The GetSheet method returns a Microsoft Excel sheet according to the sheet Identifier
'ExcelApp - The Microsoft Excel application which is the parent of the requested sheet
'sheetIdentifier - The name or the number of the requested Microsofr Excel sheet
'return Nothing on failure

Function GetSheet(ExcelApp, sheetIdentifier) 'As Excel.worksheet


On Error Resume Next
Set GetSheet = ExcelApp.Worksheets.Item(sheetIdentifier)
On Error GoTo 0
End Function

'The InsertNewWorksheet method inserts a new worksheet into the active workbook or
'the workbook identified by the workbookIdentifier. The new worksheet will get a
default
'name if the sheetName parameter is empty, otherwise the sheet has the sheetName
'as its name.
'Return - The new sheet as an object
'ExcelApp - The Microsoft Excel application object into which the new worksheet
should be added
'workbookIdentifier - An optional identifier of the worksheet into which the new
worksheet should be added
'sheetName - The optional name of the new worksheet.

Function InsertNewWorksheet(ExcelApp, workbookIdentifier, sheetName) 'As


Excel.worksheet
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
'If the workbookIdentifier is empty, work on the active workbook
If workbookIdentifier = "" Then
Set workbook = ExcelApp.ActiveWorkbook
Else
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
Set InsertNewWorksheet = Nothing
Err = 0
Exit Function
End If
On Error GoTo 0
End If
sheetCount = workbook.Sheets.Count
workbook.Sheets.Add , sheetCount
Set worksheet = workbook.Sheets(sheetCount + 1)
'If the sheetName is not empty, set the new sheet's name to sheetName
If sheetName <> "" Then
worksheet.Name = sheetName
End If
Set InsertNewWorksheet = worksheet
End Function

'The RenameWorksheet method renames a worksheet'


'ExcelApp - The Microsoft Excel application that is the worksheet's parent
'workbookIdentifier - The worksheet's parent workbook identifier
'worksheetIdentifier - The worksheet's identifier
'sheetName - The new name for the worksheet

Function RenameWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier,


sheetName) 'As String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Workbook Identifier"
Err = 0
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RenameWorksheet = "Bad Worksheet Identifier"
Err = 0
Exit Function
End If
worksheet.Name = sheetName
RenameWorksheet = "OK"
End Function

'The RemoveWorksheet method removes a worksheet from a workbook


'ExcelApp - The Microsoft Excel application that is the worksheet's parent
'workbookIdentifier - The worksheet's parent workbook identifier
'worksheetIdentifier - The worksheet's identifier

Function RemoveWorksheet(ExcelApp, workbookIdentifier, worksheetIdentifier) 'As


String
Dim workbook 'As Excel.workbook
Dim worksheet 'As Excel.worksheet
On Error Resume Next
Err = 0
Set workbook = ExcelApp.Workbooks(workbookIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Workbook Identifier"
Exit Function
End If
Set worksheet = workbook.Sheets(worksheetIdentifier)
If Err <> 0 Then
RemoveWorksheet = "Bad Worksheet Identifier"
Exit Function
End If
worksheet.Delete
RemoveWorksheet = "OK"
End Function

'The CreateNewWorkbook method creates a new workbook in the Microsoft Excel


application
'ExcelApp - The Microsoft Excel application to which an new Microsoft Excel
workbook will be added

Function CreateNewWorkbook(ExcelApp)
Set NewWorkbook = ExcelApp.Workbooks.Add()
Set CreateNewWorkbook = NewWorkbook
End Function

'The OpenWorkbook method opens a previously saved Microsoft Excel workbook and
adds it to the Application
'excelApp - The Microsoft Excel application to which the workbook will be added.
'path - The path of the workbook that will be opened
'Returns Nothing on failure

Function OpenWorkbook(ExcelApp, path)


On Error Resume Next
Set NewWorkbook = ExcelApp.Workbooks.Open(path)
Set OpenWorkbook = NewWorkbook
On Error GoTo 0
End Function
'The ActivateWorkbook method sets one of the workbooks in the application as the
active workbook
'ExcelApp - The workbook's parent Microsft Excel application
'workbookIdentifier - The name or the number of the workbook

Sub ActivateWorkbook(ExcelApp, workbookIdentifier)


On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Activate
On Error GoTo 0
End Sub

'The CloseWorkbook method closes an open workbook


'ExcelApp - The parent Microsoft Excel application of the workbook
'workbookIdentifier - The name or the number of the workbook

Sub CloseWorkbook(ExcelApp, workbookIdentifier)


On Error Resume Next
ExcelApp.Workbooks(workbookIdentifier).Close
On Error GoTo 0
End Sub

'The CompareSheets method compares two sheets.


'If there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - The Microsoft Excel sheets to be compared
'startColumn - The column to start comparing in the two sheets
'numberOfColumns - The number of columns to be compared
'startRow - The row to start comparing in the two sheets
'numberOfRows - The number of rows to be compared

Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow,


numberOfRows, trimed) 'As Boolean
Dim returnVal 'As Boolean
returnVal = True
'If one of the sheets does not exist, do not continue the process
If sheet1 Is Nothing Or sheet2 Is Nothing Then
CompareSheets = False
Exit Function
End If
'Loop through the table and fill values into the two worksheets
For r = startRow to (startRow + (numberOfRows - 1))
For c = startColumn to (startColumn + (numberOfColumns - 1))
Value1 = sheet1.Cells(r, c)
Value2 = sheet2.Cells(r, c)
'If 'trimed' equals True then user wants to ignore blank spaces
If trimed Then
Value1 = Trim(Value1)
Value2 = Trim(Value2)
End If
'if the values of a cell are not equal in the two worksheets
'create an indicator that the values are not equal and set the return value
'to False
If Value1 <> Value2 Then
Dim cell 'As Excel.Range
sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is
'" & Value1 & "'."
Set cell = sheet2.Cells(r, c)
cell.Font.Color = vbRed
returnVal = False
End If
Next
Next
CompareSheets = returnVal
End Function

'***********************************************
'Main Script which calls all above the functions.

Dim ExcellApp 'As Excel.Application


Dim excelSheet1 'As Excel.worksheet
Dim excelSheet2 'As Excel.worksheet
Set ExcelApp = CreateExcel()
'Create a workbook with two worksheets
ret = RenameWorksheet(ExcelApp, "Book1", "Sheet1", "Example1 Sheet Name")
ret = RenameWorksheet(ExcelApp, "Book1", "Sheet2", "Example2 Sheet Name")
'Save as the workbook under a different name
ret = SaveWorkbook(ExcelApp, "Book1", "E:\Example1.xls")
'Fill the worksheets
Set excelSheet1 = GetSheet(ExcelApp, "Example1 Sheet Name")
Set excelSheet2 = GetSheet(ExcelApp, "Example2 Sheet Name")
For column = 1 to 10
For row = 1 to 10
SetCellValue excelSheet1, row, column, row + column
SetCellValue excelSheet2, row, column, row + column
Next
Next
'Compare the two worksheets
ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, False)
If ret Then
MsgBox "The two worksheets are identical"
End If
'Change the values in one sheet
SetCellValue excelSheet1, 1, 1, "Yellow"
SetCellValue excelSheet2, 2, 2, "Hello"
'Compare the worksheets again
ret = CompareSheets(excelSheet1, excelSheet2, 1, 10, 1, 10, True)
If Not ret Then
MsgBox "The two worksheets are not identical"
End If
'Save the workbook by index identifier
SaveWorkbook ExcelApp, 1, ""
'Close the Microsoft Excel application
CloseExcel ExcelApp

How to add two dollar amounts


'''''' To add the $ amounts''''''''''''''''

amount1 = inputbox("Enter the first dollar amount")


''''''Enter the amount with $ symbol Ex - $ 2000

amount2 = inputbox("Enter the second dollar amount")


'''''Enter the amount with $ symbol Ex - $ 3000

lnt1=len (amount1)
'To get the length of the dollar amount
lnt2=len(amount2)
' To get the length of the dollar amount

aamount1 = Right(amount1,lnt1-1)
'''''' To remove the dollar symbol and get the actual amount

aamount2= Right(amount2,lnt2 - 1)
''''''To remove the dollar symbol and get the actual amount

msgbox Cint(aamount1)+Cint(aamount2)

Search for a word and replace the word with a new word then save
as a different file name

'Before this script executes, you need to have a "Greetings.doc" in C


drive and it contains some information. In that information each line is
contains a word "Good". Now my objective is to Replace the word "Good"
with "Bad". And save file with new name.
#####################################################
###########

Set Word = CreateObject("Word.Application")


Word.Visible = TRUE
Set WordDoc=Word.Documents.Open ("C:\Greetings.doc")
Do
With Word.Selection.Find
.Text = "Good"
.Replacement.Text = "Bad"
.Forward = True
.wrap=1
.Format = False
.MatchWholeWord = True
End With
Word.Documents.Application.Selection.Find.Execute
If Word.Selection.Find.Found Then
Word.Selection.Range="bad"
else
Exit Do
End If
Loop
WordDoc.SaveAS "C:\BadGreetings.doc"

Script for adding and ramoving Object repository to an action

Here i have written two functions for adding and removing Object
Repositories for an action call these function with object repository
path.
'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@
'Adding Repository to an action
Function AddRepositorytoCurrentAction(RepPath)

Dim qtApp,qtRepositories, actName

actName=Environment.Value("ActionName")

Set qtApp = CreateObject("QuickTest.Application")


Set qtRepositories = qtApp.Test.Actions(actName).ObjectRepositories

If qtRepositories.Find(RepPath) = -1 Then
qtRepositories.Add RepPath, 1
End If

If rmvPosition<> -1 Then
Reporter.ReportEvent micPass,"Adding Object Repository","Object
Repository is Succesfully Added to the Action "&actName
else
Reporter.ReportEvent micFail,"Adding Object Repository","Object
Repository is not Added to the Action "&actName
End If

qtApp= Nothing
qtRepositories= Nothing
End Function

'Remove repository from an action


Function RemoveRepositoryfromCurrentAction(RepPath)
Dim qtApp,qtRepositories, actName

actName=Environment.Value("ActionName")

Set qtApp = CreateObject("QuickTest.Application")


Set qtRepositories = qtApp.Test.Actions(actName).ObjectRepositories

rPosition=qtRepositories.Find(RepPath)

qtRepositories.Remove rPosition

rmvPosition=qtRepositories.Find(RepPath)

If rmvPosition= -1 Then
Reporter.ReportEvent micPass,"Removing Object Repository","Object
Repository is Succesfully Removed From the Action "&actName
else
Reporter.ReportEvent micFail,"Removing Object Repository","Object
Repository is not Removed From the Action "&actName
End If

qtApp= Nothing
qtRepositories= Nothing

End Function

'@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@

To get the tool tip of the Link

l_ToolTip=Browser( bName).Page( pName).Link( lName).object. title


msgbox l_ToolTip
This statement will bring the tooltip of a link.

How to click on Dynamic Links

Here is the script to click on the dynamic Links in table. Even though if
any link are dynamic we can get control on the links by using index.

'########### ######### ######### ######### #########


######### #########
Set TblObj=Browser( BrowserProp) .Page(PageProp) .WebTable(
TableProp)

r_Count=TblObj. RowCount

For r=1 to r_Count


c_Count=TblObj. ColumnCount( r)

For c=1 to c_Count

chItems_Count= TblObj.ChildItem Count(r,c, "Link")

For ItemIndex=0 to chItems_Count- 1


Set ch_Item=TblObj. ChildItem( r,c,"Link" ,ItemIndex)
Print ch_Item.object. title
ch_Item.click
' Specify the required operations after clicking on link
' Make sure that again you should navigate to the same page to get other
links tooltip
'Or to click on other Links
Next

Next
Next
'########### ######### ######### ######### #########

How to use Classes in QTP

Here i am giving an useful information about how to use classes in QTP.

Before going to that we will discuss about using functions in QTP.

If there is a function in our script like this

'*********** ********* ********* ********* ********* ********* **


Function Demo(a,b)
demo=a+b
End Function
'*********** ********* ********* ********* ********* ********* **

This is a function to add two numbers.


To call this function we write
'*********** ********* *****
val=demo(2,3)
msgbox val
'*********** ********* *****
We can store the functions in library files (.vbs) and to use this function,
Library should be associated to the QTP Test or library file should be
executed by QTP Test using ExecuteFile statement.
This means we can use the functions which are written in QTP Script or
in Library files by associating it or by executing it.

But this is not possible when using classes in our QTP Test. If we want to
use a class which is there in the libraryfile its mandotory that the library
should be executed using Executefile statement.
Classes will not work which are there in associated libraries. Here is an
example...

'*********** ********* ********* ********* ********* **


Class Maths
Function Add1(a,b)
add1=a+b
End Function

Function sub1(a,b)
sub1=a-b
End Function

End Class
'*********** ********* ********* ********* ********* **
If the above code is there with in the test script then the usage of this
class will be like this
'*********** ********* ********* ********* ********* **
Set mat=New Maths
val=mat.add1( 2,3)
msgbox val
'*********** ********* ********* ********* ********* **
If the class code is there with in the library file then the usage of this
class will be like this
'*********** ********* ********* ********* ********* **
ExecuteFile (Library Path)
Set mat=New Maths
val=mat.add1( 2,3)
msgbox val
'*********** ********* ********* ********* ********* **
This class will not work If you just associate the library with in the
File--> Settings --> Resources
But there is a way of using the classes even though if it is in associated
library.

First Method:
Where ever the class is declared in the library it self create the class
instance and use it in your qtp script.
'*********** ********* ********* ********* ********* **
Set mat=New Maths

Class Maths
Function Add1(a,b)
add1=a+b
End Function

Function sub1(a,b)
sub1=a-b
End Function

End Class
'*********** ********* ********* ********* ********* **
To Use this class
'*********** ********* *
val=mat.add1( 2,3)
msgbox val
'*********** ********* *

Second Method:
Create a function which is returning class object by creating instance of
the class.
'*********** ********* ********* ********* ********* **
Function mat()
Set mat=New Maths
End Function
Class Maths
Function Add1(a,b)
add1=a+b
End Function

Function sub1(a,b)
sub1=a-b
End Function

End Class
'*********** ********* ********* ********* ********* **
To Use this class
'*********** ********* *
Set mth=mat ' mat is a function which will return the class instance
val=mth.add1( 2,3)
msgbox val
'*********** ********* *

Вам также может понравиться