Está en la página 1de 13

WORKING WITH QTP

Functional Test with QTP

Sunday, May 3, 2009


FIND CELL Value in EXCEL VB

Some Time we have to Check that particular Cell Value Exist or Not and required the Cell
address
rem this function return the first find Cell address value of your Excel sheet & Change
Color of Cell find value
rem input parameter xlFilePath := xls file path || FindValue =value which need to be find
dim sXLpath , FindValue ,getCellAddress
sXLpath =”C:\RajivKumarNandvani.xls” rem define xls file path
FindValue =”Rajiv” rem check rajiv in cell exist or not
getCellAddress = FindCellAddress(sXLpath ,FindValue )
msgbox getCellAddress

Public function FindCellAddress(Byval xlFilePath ,byval FindValue )

Set ObjAppExcel = CreateObject(”Excel.Application”)


rem Disable alerts
ObjAppExcel.DisplayAlerts = False
rem Add a workbook to the Excel App
ObjAppExcel.Workbooks.open(xlFilePath)
REm Get the object of the first sheet in the workbook
Set objectSheet = ObjAppExcel.Sheets(”Sheet1″)
rem define the range from A1 to last column address and filnd the value in range
set objValueFind = objectSheet.UsedRange.Find(FindValue)
If not objValueFind is nothing Then
CellAddress =objValueFind.address
FindCellAddress=replace(objValueFind.address,”$”,”")
FindCellAddress=replace( FindCellAddress,”1″,”")

Do

set objValueFind = objectSheet.UsedRange.FindNext(objValueFind )

Loop While Not objValueFind Is Nothing And objValueFind.Address <> CellAddress

Exit function
End If
rem if not found then return the Empty
FindCellAddress=”NOT FOUND”

Set objValueFind =nothing


Set objectSheet =nothing
Set ObjAppExcel =nothing
End Function
Posted by RajivKumarNandvani at 4:56 AM 0 comments
Labels: CELLADDRESS, EXECL, FIND CELL VALUE, SHEET, USEDRANGE

Get EXCEL COLUMN VB / in Array

sXLpath =”C:\TESTXML\Rajiv.xls”
myArray = GetALLColumn(sXLpath)

Public function GetALLColumn(Byval xlFilePath )


rem define array column
Dim AllColumn()
Set ObjAppExcel = CreateObject(”Excel.Application”)
rem Disable alerts
ObjAppExcel.DisplayAlerts = False
rem Add a workbook to the Excel App
ObjAppExcel.Workbooks.open(xlFilePath)
‘Get the object of the first sheet in the workbook
Set objectSheet = ObjAppExcel.Sheets(”Sheet1″)
rem count used Column in sheet
nColumnCount =objectSheet.UsedRange.Columns.Count

ReDim preserve AllColumn(nColumnCount-1)


For i=0 to nColumnCount-1
AllColumn(i) =objectSheet.Cells(1,i+1).value

Next

GetALLColumn =AllColumn
Set objectSheet =nothing
Set ObjAppExcel =nothing
End Function

Posted by RajivKumarNandvani at 4:53 AM 0 comments


Labels: ARRAY., cloumn, EXCEL, VB EXCEL

Select Radio Button QTP


Rem**************************************************************************
************

Rem This function select the radio button with specified number of index
REM Input objRadiobutton:= radiobutton object intenetexplorer exe || nIndex:= number
of specifed radio button which need to be rem select
REM Output(ReturnType) := None
REM Created: 07/April/2009 Rajiv Kumar Nandvani ## REM Changed:MM/DD/YYYY

REM*************************************************************************
**

set objRadiobutton =Browser(”Browser”).Page(”Page”)..WebRadio(”Radio_Group”)

nIndex =1 rem first radio button select

call fn_RadioButtonSelect(objRadiobutton,nIndex)

Public Function fn_RadioButtonSelect( byref objRadiobutton,byval nIndex)

sItems= objRadiobutton.GetROProperty(”all items”)


sItems=split(sItems,”;”)
nIndex =nIndex-1

If nIndex =< (ubound(sItems) ) Then


objRadiobutton.select sItems(nIndex)
else
Print “Please check number of radio button”

End If

Rem Clear All the Refrences to the Objects


Set objRadiobutton =nothing
End Function

Posted by RajivKumarNandvani at 4:49 AM 0 comments


Labels: GetROProperty, QTP, radio button

Work With text box( Windows WinEdit box) QTP

In most cases, double-clicking on a data input field is the preferable method of selection;
furthermore, it is usually necessary versus a single mouse click on the object. Double –clicking
selects the all of the data in that field so that it can be replaced with the new data. A single- click
operation, may only place the cursor in the input control , selecting none of the existing data and
normally activates the insert mode . Not good. The existing data is not replaced with the new
value. In some applications where multiple words or value separated by spaces can lives in a
single edit box. We have found the even double-clicking may not get all of the text selected and
ready for replacement. In this case, the method that consistently ensures that all of the data is
selected is this: navigate to control via keyboard control, such as tabbing, right arrow or mouse
click. Once the cursor is placed into the control, record these keystrokes:

Ctrl + Home
Ctrl + Shift + End
Delete

Like
Dialog(”Login”).WinEdit(”Agent Name:”).Type micCtrlDwn + micHome + micCtrlUp
Dialog(”Login”).WinEdit(”Agent Name:”).Type micCtrlDwn + micShiftDwn + micEnd +
micShiftUp + micCtrlUp

Posted by RajivKumarNandvani at 4:48 AM 0 comments

Work With List Box QTP

When we use list box Object in QTP. QTP perform following operation on listbox . like

Browser(”Browser”).Page(”Page”)..WebList(”ListBox”).Select “ListBoxValue”

It select the value from List Box that value must be present in list box otherwise QTP give an
error like that

“Cannot identify the specified item of the ListBox object. Confirm that the specified item is
included in the object’s item collection.”

So before selection any value in list box Always insure the value you are going to select in list
box must be present by use this method/Function

dim objListBox, sValuematch ,bTrue


set objListBox = Browser(”Browser”).Page(”Page”)..WebList(”ListBox”)
sValuematch =”Type Value that need to be check”
bTrue = fn_Valuematch_for_weblistbx(objListBox ,sValuematch )
if bTrue =True then
Browser(”Browser”).Page(”Page”)..WebList(”ListBox”).Select “ListBoxValue”
end if

REM*************************************************************************
************************************
REM ” this function Check the value u define match With in WEBListbox or Not if match return
true otherwise False
Public Function fn_Valuematch_for_weblistbx(byval m_listboxobject, byval m_valuematch)
”check is m_listboxobject object or not
If IsObject(m_listboxobject ) = true and IsNull(m_valuematch) = false Then
Dim m_Getallfield,m_arAllfield,m_val,m_actual
m_arAllfield = m_listboxobject.GetROProperty(”all items”)
m_arAllfield =Split (m_arAllfield,”;”)
For each element in m_arAllfield
If m_valuematch = element then ‘ compare the text
fn_Valuematch_for_weblistbx=true ” if value match then return true & exit thr loop
exit for
else
fn_Valuematch_for_weblistbx = false
end if
Next
else
print “Error wrong Parameter for function fn_Valuematch_for_listbx”,”Check paramenter value”
End If
End Function
REM*****************************
Posted by RajivKumarNandvani at 4:29 AM 0 comments
Labels: ListBox, QTP, WebList

Performance increase in table lookup functions QTP

Using object properties instead of QTP standard functions will improve the performance of QTP
tests significantly. In our case, we often want to lookup the location of a certain value in a
WebTable. QTP provides several functions to read out data from a table, but is slow when used
iterating the table (like two for loops, one iterating the rows, the embedded second one iterating
the columns per row).

Example of a conservative way to do this:

Public Function LocateTextInTable(byRef tbl, textToFind, byRef row, byRef col)

For row = 1 to tbl.RowCount


For col = 1 to tbl.ColCount
If tbl.GetCellData(row, col) = textToFind then
LocateTextInTable = True
Exit function
End if
Next
Next

row = -1 : col = -1
LocateTextInTable = False
End Function
The crux is this: .GetCellData is not a very fast method and with a table, consisting of 30 rows
and 10 columns, this method is iterated up to 300 times in the most worse case scenario (= text
not found).

A faster way to retrieve the data is through the Document Object Model (DOM). This allows you
to use the more native properties of an object with the sacrifice of some ease of use.

A table consists of row elements and each row element contains one or more cells. We can
iterate them just the same way as we did with the function above:

Public Function LocateTextInTableDOM(byRef tbl, textToFind, byRef row, byRef col)

Dim objRow, objCell

row = 1 : col = 1

For each objRow in tbl.object.Rows


For each objCol in objRow.Cells
If objCol.Value = textToFind then
LocateTextInTableDOM = True
Exit function
End if
col = col + 1
Next
row = row + 1
Next

row = -1 : col = -1
LocateTextInTableDOM = False
End Function

Posted by RajivKumarNandvani at 4:18 AM 0 comments


Labels: EXCEL, For loop, QTP, WebTable

Importance of Parenthes when we call Function or Sub QTP

Whenever you define a function with using argument always define the argument type by using
ByVal OR ByRef Because if u not define the argument type by default it take ByRef

Parenthesis matter in QTP (and VBScript). And they surely make a difference. During
debugging a function call. There was different behaviour between these two function calls:
foo(bar)
call foo(bar)
Passing an argument to a function surrounded by parenthesis means: “Protect me” or in other
words: treat me as byVal even if it is defined in the function as byRef.
Example:
sub samplesub (a, b) ‘ a and b are by default handled as byRef
a=a+b
end sub

And this is happening when we call samplesub:


x=1
y=2
z=4
samplesub x, y
samplesub (z), y
msgbox x ‘ displays “3″
msgbox z ‘ displays “4″ because z was passed as if it was passed byVal

The same applies when you call a function:

function samplefunc(c)
c = c^2-1
samplefunc = (c mod 2 = 1)
end function

q=8
samplefunc q
msgbox q ‘ returns 63

‘ When you accidentally forgot to call:


p=9
samplefunc(p)
msgbox p ‘ returns 9, because p is returned byVal

‘ With call:
r = 10
call samplefunc(r)
msgbox r ‘ returns 99, because r is returned byRef

‘ With call and argument protected:


s = 11
call samplefunc( (s) )
msgbox s ‘ returns 11, s is returned byVal

‘ And a last example of a function call with multiple argument with combined protection:
call multifunc( (IamProtected), IamUnprotected )

Rules in short:
A sub/function call with an argument in protected mode overrides a byRef in the function.
A sub/function call with an argument in unprotected mode is returned byRef by default unless it
is overridden in the function by a byVal.
An literal or const is always returned byVal.

Syntax proposal:
OK, it is ugly, but if you use parenthesis because they are part of the call, you should use them
with spaces between the first and last argument and no space between the function:

call f( a, b )

If you want to use arguments in protected mode, you should use no spaces between the
parenthesis and the arguments, but do use them between the function/sub and the parenthesis
belonging to the function/sub call:

f (a), (b)
or
call f( (a), (b) )

Delete Cookies and Temprary internet files VB QTP

rem ********************************

rem delete cookies

call fn_DeletesubFolderAndFiles(”C:\DOCUME~1\%USERNAME%\Cookies”)

rem *********************************

rem rem delete Temporary internet files

call fn_DeletesubFolderAndFiles(”C:\DOCUME~1\%USERNAME%\Locals~1\Tempor~1″)

rem ***********************************

REM *************************************************************************

REM Function fn_DeletesubFolderAndFiles(path)

Rem this Function delete the files & subfolder under the specified path

REM Input spath := Files path or parent Folder path

REM Output(ReturnType) := None

REM Note := IF file Protected then it will not delete without giving Error
REM Created: 17/April/2009 Rajiv Kumar Nandvani ## Changed:MM/DD/YYYY

REM *************************************************************************

Public Function fn_DeletesubFolderAndFiles(spath)

on Error Resume Next

rem Create File System object

set objFileSystem = CreateObject(”Scripting.FileSystemObject“)

rem Create Window Shel object

Set objWshShell = CreateObject(“WScript.Shell“)

Rem get Folderpath under which file present

Set objoFolder = objFileSystem.GetFolder(objWshShell.ExpandEnvironmentStrings(spath))

rem get count the files under the folder and loop run for delete the files

For Each oFile In objoFolder.files

On Error Resume Next

objFileSystem.DeleteFile oFile

Err.clear

Next

rem get count the subfolders under the folder and loop run for delete the subfolders

For Each oSubFolder In objoFolder.SubFolders

On Error Resume Next

objFileSystem.DeleteFolder oSubFolder

Err.clear

Next

rem clear the object


set objFileSystem = nothing

set objWshShell = nothing

set objoFolder = nothing

Err.clear

End function

Posted by RajivKumarNandvani at 5:14 AM 0 comments


Labels: Cookies, CreateObject("scripting.filesystemobject"), FileSystemObject, Shell,
Temporary internet files, WScript.Shell

Close All open Browser QTP VB

‘ This function Close All open Browser


REM *************************************************************************

REM this function close All open browser

Public Function fn_CloseAllBrowser()


While Browser(”CreationTime:=0″).Exist
Browser(”CreationTime:=0″).Close
Wend
End Function

REM
*************************************************************************ss

Posted by RajivKumarNandvani at 5:12 AM 0 comments


Labels: QTP, WEB

Close Application Process QTP

REM This function kill the given process exe through task manager
rem example call fn_CloseApplication(”EXCEL.EXE”)

Public Function fn_CloseApplication( byval sApplicationExe)


Dim strComputer
Dim objWMIService
Dim colProcesses
Dim objProcess
strComputer = “.”
Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)
Set colProcesses = objWMIService.ExecQuery (”Select * from Win32_Process Where Name =
‘”&sApplicationExe&”‘”)
For Each objProcess in colProcesses
objProcess.Terminate()
Next
Set objWMIService = Nothing
Set colProcesses=Nothing
End Function

Posted by RajivKumarNandvani at 5:04 AM 0 comments


Labels: Win32_Process, wmiservice

Get current DATETIME through VB QTP/Create unique file or folder

Some Time we want create a folder Or File with unique name then we current date time
value for creating the file or folder that we can use this method for create the file OR folder
as decribed here

REM this function return the current date time in text format

REM Function fn_GetDateTimeText() This function return currentdatetime in Text format


REM this will remove the specail charactor from currentdatetime & replace with _ underscore
REM Input := None
REM Output(ReturnType) := return currentdatetime in Text format

Public Function fn_GetDateTimeText

Dim sDateTime
sDateTime = now
sDateTime =replace(sDateTime,”:”,”_”)
sDateTime =replace(sDateTime,”>”,”_”)
sDateTime =replace(sDateTime,”<”,”_”)
sDateTime =replace(sDateTime,”/”,”_”)
sDateTime =replace(sDateTime,”|”,”_”)
sDateTime =replace(sDateTime,”\”,”_”)
sDateTime =replace(sDateTime,”*”,”_”)
sDateTime =replace(sDateTime,”"”",”_”)
sDateTime =replace(sDateTime,”#”,”")
fn_GetDateTimeText =sDateTime
End Function

dim sGetCurrentDateTime

sGetCurrentDateTime = fn_GetDateTimeText()

Set objFSO =CreateObject(”Scripting.FileSystemObject”)


rem create text file

objFSO.CreateTextFile(“c:/” & sGetCurrentDateTime & “.txt” , True)

rem create folder

objFSO.CreateFolder(“c:/” & sGetCurrentDateTime & “.txt” , True)

Posted by RajivKumarNandvani at 5:02 AM 0 comments


Labels: CreateObject("scripting.filesystemobject"), CreateTextFile, date, NOW, QTP,
reateFolder, time

Check XML File Valid OR Not VB QTP

REM ************************************************
Rem This Function Check XML File Valid OR not if File not valid XML then return False Else
True
REM Function fn_CheckXMLValid( sXMLfilepath)
REM Input sXMLfilepath := XMLfilepath
REM Output(ReturnType) := True or False
REM Created: 21/April/2009 Rajiv Kumar Nandvani ## Changed:MM/DD/YYYY

REM *************************************************************************

Public Function fn_CheckXMLValid(byval sXMLfilepath)


rem create XML object
Set xmlDoc = CreateObject( “Microsoft.XMLDOM” )
xmlDoc.Async = “False”
Rem load XML File
xmlDoc.Load( sXMLfilepath )
If xmlDoc.parseError.errorCode<>0 Then
fn_CheckXMLValid=False
else
fn_CheckXMLValid=True
End If
Set xmlDoc = nothing

End Function

REM ************************************************

Posted by RajivKumarNandvani at 5:00 AM 0 comments


Labels: CreateObject( "Microsoft.XMLDOM" ), QTP, VB, XML

Get Column Address Excel VB / Find Column


Some Time we have to Check that particular column Exist or Not abd required the column
address
rem this function return the column address of your Excel sheet
rem input parameter xlFilePath := xls file path || FindColumn =column value which need
to be check
dim sXLpath , FindColumn ,getColumnAddress
sXLpath =”C:\RajivKumarNandvani.xls” rem define xls file path
FindColumn =”Rajiv” rem check rajiv in column exist or not
getColumnAddress = FindColumnAddress(sXLpath ,FindColumn )
msgbox getColumnAddress
Public function FindColumnAddress(Byval xlFilePath ,byval FindColumn )

Set ObjAppExcel = CreateObject(”Excel.Application”)


rem Disable alerts
ObjAppExcel.DisplayAlerts = False
rem Add a workbook to the Excel App
ObjAppExcel.Workbooks.open(xlFilePath)
‘Get the object of the first sheet in the workbook
Set objectSheet = ObjAppExcel.Sheets(”Sheet1″)
rem count used Column in sheet
nColumnCount =objectSheet.UsedRange.Columns.Count
rem get the last column address
c =replace(objectSheet.Cells(1,nColumnCount).address,”$”,”")
rem define the range from A1 to last column address and filnd the value in range
set objValueFind = objectSheet.Range(”A1:”&c).Find(FindColumn)
If not objValueFind is nothing Then
FindColumnAddress =replace(objValueFind.address,”$”,”")
FindColumnAddress =replace(FindColumnAddress,”1″,”")
Exit function

End If
rem if not found then return the Empty
FindColumnAddress =”NOT FOUND”

Set objValueFind =nothing


Set objectSheet =nothing
Set ObjAppExcel =nothing
End Function

También podría gustarte