Skip to main content

QTP Scripts examples...

1. Script for sending a mail using outlook express.

Dim objOutlookMsg,objOutlook
Set objOutlook = CreateObject(”Outlook.Application”)
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
objOutlookMsg.To = “”
objOutlookMsg.CC = “ “
objOutlookMsg.BCC = “”
objOutlookMsg.Subject = “test”
objOutlookMsg.Body = “”
objOutlookMsg.Attachments.Add “C:\Documents and Settings\Desktop\testreport.txt”
objOutlookMsg.Send

2. Script for opening a Notepad file.

In Expert view write a builtin funtion
invokeapplication”c:/whatever the path”
Run

Dim a
Set a = WScript.CreateObject (”WSCript.shell”)
a.run “notepad.exe”

Dim oShell
Set oShell = CreateObject (”WSCript.shell”)
oShell.run “cmd/notepad.exe”
Set oShell = Nothing

DsystemUtil.Run “Notepad.exe”

3. Script for connecting the oracle database

public void connectDB()
{
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3
Set objCon=CreateObject(”ADODB.Connection”)
Set objRec=CreateObject(” ADODB.Recordset”)
objCon.Open “DRIVER={Oracle in OraHome92};SERVER={Servername};UID={Username};PWD={Password};DBQ={Dbnmae}”
objRec.CursorLocation = adUseClient
objRec.Open “Select {Col name} from tablename”,objCon,adOpenStatic,adLockOptimistic
While(objRec.EOF)
objRec.MoveNext
Msgbox ”Result” & objRec.Fields.Item(”{Col name}”)& vbCrLf
Wend
objRec.Close
objCon.Close
Set objRec=Nothing
Set objCon=Nothing
Msgbox “Executed Sucessfully”
}

Use code only that which is inside the function connectDB

4. Two ways to connect QC with QTP.

Connect manually

1. To connect to TD from QTP follow the steps…
2. Open Qtp ==> Tools ==>
3. Select TestDirector Connection ==>
4. In Server Connction Box Enter TD address(URL of TD) ==>
5. Click Connect==>
6. In project Connection Box Enter the Details Domain,Project,User name and Password ==>
7. Click Connect If you want to reconnect on startup check the reconnect on startup and save password for reconnection on startup.
8. Then close.

Using Script

Set qtApp = CreateObject(”QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.TDConnection. Connect “URL”, “DOMAIN”, “PROJECT”, “USERNAME”, “PASSWORD”, False

5. Retrieve Data from Excel sheet

Dim FilePath, Excelone,ExcelSheet,Val
Set FilePath= CreateObject(”srcfilepath”)
Set ExcelSheet = FilePath.GetSheet(sheetid)
Set Val= ExcelSheet.ActiveSheet.Cells(1,1).value

‘Below script for creating an excel sheet with values 1,2,3
Dim Excel,ExcelSheet
Set Excelone=CreateObject(”Excel.Application”)
Set ExcelSheet=CreateObject(”Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing

6. Some more stuff related to QTP Script.

Set Word = CreateObject(”Word.Application”)
oWord.DisplayAlerts = False
oWord.Visible = False
oWord.documents.open “testWordDoc.doc”
Set Doc = oWord.ActiveDocument
Set Range = oDoc.content
oRange.ParagraphFormat.Alignment = 0
oRange.insertafter vbcrlf ‘& ” ” & vbcrlf
oRange.collapse(0)
oRange.InlineShapes.AddPicture “ImagePath.bmp”, False, True
oWord.ActiveDocument.Save
oWord.Application.Quit True
Set Range = Nothing
Set Doc = Nothing
Set Word = Nothing

‘————————————————————–

Cmd.activeconnection=”Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User ID=sa;Initial Catalog=pubs;

Dim res,cmd,sql
Set Res=createobject(”adodb.recordset”)
Set Cmd=createobject(”adodb.command”)
Cmd.activeconnection=”Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User ID=sa;Initial Catalog=pubs;Data Source=192.168.0.69″
Cmd.CommandType = 1
sql=”select emp_id,fname from dbo.employee”
Cmd.CommandText = sql
Set res = Cmd.Execute()
i=1

While not res.eof
logid = res(”emp_id”).value
logname=res(”fname”).value
print logid
print logname
i=i+1
res.movenext
wend
Set res = nothing
Set cmd.ActiveConnection = nothing
Set Cmd= nothing

‘————————————————————–

Set ExcelObj = CreateObject(”Excel.Application”)
aatype=”F:\templet.xls”
ExcelObj.Workbooks.Open(aatype)
Set NewSheet = ExcelObj.Sheets.Item(2)
Dim rs,sq,pkey
set conn=createobject(”adodb.connection”)
set rs=createobject(”adodb.recordset”)
set rs1=createobject(”adodb.recordset”)
conn.open= “Provider=OraOLEDB.Oracle.1;Password=*;Persist Security Info=True;User ID=*;SERVER=*;Data Source=*;DBQ=*;”
sql=”select * from table”
rs.open sql,conn
i=1
do while not rs.eof
values1=rs(”pkey”)
values2=rs(”name”)
NewSheet.Cells(i+1,1).Value =values1
NewSheet.Cells(i+1,2).Value =values2
i=i+1
rs.movenext
Loop

‘————————————————————–

ExcelObj.ActiveWorkbook.Saveas “F:\data.xls”
ExcelObj.Quit
Set ExcelObj = Nothing
rs.close
set rs=nothing
conn.close
set conn=nothing

‘————————————————————–

Dim Excel,ExcelSheet
Set Excelone=CreateObject(”Excel.Application”)
Set ExcelSheet=CreateObject(”Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing

‘————————————————————–

Set fs=CreateObject(”excel.application”)
fs.Visible=True
Set excelbook=fs.Workbooks.Add
Set excelsheet=excelbook.worksheets(1)
excelsheet.cells(1,1)=”??”
excelsheet.saveas “e:\1.xls”
excelsheet.application.quit
fs.Quit

‘————————————————————–

set fs=createobject(”excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(”f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=”Test”
excbook.save
fs.quit

‘————————————————————–

Dim qtApp ,pDefColl,pDef ,rtParams,rtParam
Set qtApp = CreateObject(”QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.Open “C:\Test1″
Set pDefColl = qtApp.Test.ParameterDefinitions
cnt = pDefColl.Count
Indx = 1
While Indx <= cnt
Set pDef = pDefColl.Item(Indx)
Indx = Indx + 1
Wend
Set rtParams = pDefColl.GetParameters()
Set rtParam = rtParams.Item(”InParam1″)
rtParam.Value = “songfun”
qtApp.Test.Run , True, rtParams
MsgBox rtParams.Item(”OutParam1″).Value

‘————————————————————–

Dim a,b,c
Set a = createobject(”excel.application”)
a.visible = true
Set b = a.workbooks.add
Set c = b.worksheets(1)
c.cells(1,1) = “1″
c.cells(1,2) = “2″
c.cells(1,3) = “3″
c.saveas “e:\testtwo.xls”
c.application.quit
a.quit

‘————————————————————–

set fs=createobject(”excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(”f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=”Test1″
excbook.save
fs.quit

‘————————————————————–

Set alapp=createobject(”Excel.Application”)
alapp.application.visible=true
Set xlbook=alapp.workbooks.open(”e:\test.xls”)
Set xlSheet = xlBook.Worksheets(”Sheet1″)
count1=datatable.GetSheet(”Action1″).getrowcount
For i=1 to count1
alapp.cells(i,1)= datatable.GetSheet(”Action1″).getparameter(”Test1″).valuebyrow(i)
Next
xlSheet.saveas “e:\1.xls”
alapp.quit
Set excel=nothing

Comments

Popular posts from this blog

Convert JSON to XML using QTP/UFT/VBScript

Sample Code : Dim strPage,strJSON,objIE strPage = "C:\Jay\JLoader.html" Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate2 strPage While objIE.Busy : Wend strJSON = "{""FirstName"":""Jay"", ""LastName"":""Krishna""}" Set objWin = objIE.document.parentWindow objWin.execScript "var jsonStr2XML = function(strJSON) { return json2xml(JSON.parse(strJSON));};" Msgbox  oWin.jsonStr2XML(strJSON) objIE.Quit In Detail: Converting The most popular data interchange format JSON(JavaScript Object Notation) to XML using QTP/UFT. Parsing JSON in UFT could be a challenge so we will use JavaScript in UFT to make it perfect. SO We need :              Java Script API  - To Convert JSON to XML                         JavaScript Files :                         http://goessner.net/download/prj/jsonxml/j

Read Outlook mail attachment and Body using Vb Script or QTP

Set olApp = CreateObject("Outlook.Application") Set olns = olApp.GetNameSpace("MAPI") Set ObjFolder = olns.GetDefaultFolder(6) j = 0 For each item1 in ObjFolder.Items        iattachCnt = item1.Attachments.Count     Print "Attachments Count: " & iattachCnt     For i = 1 to iattachCnt         Print "FileName :    " & item1.Attachments(i).FileName         Print "Display Name:   " & item1.Attachments(i).DisplayName         Print "Size: " & item1.Attachments(i).Size     Next     Print " Body : " & item1.body     Print "--------------------------------------Mail Num - " & j & " -----------------------------------------------"     j = j+1    Next

Excel Sorting By Rows and Columns

Excel Sorting By Row: Const xlAscending = 1 Const xlNo = 2 Const xlSortRows = 2 Set objExcel = CreateObject(“Excel.Application”) objExcel.Visible = True Set objWorkbook = objExcel.Workbooks.Open(“C:\Jay\Docs1.xls”) Set objWorksheet = objWorkbook.Worksheets(1) objWorksheet.Cells(1,1).activate Set objRange = objExcel.ActiveCell.EntireRow objRange.Sort objRange, xlAscending, , , , , , xlNo, , , xlSortRows set objExcel=nothing Excel Sorting By Column : Const xlAscending = 1′represents the sorting type 1 for Ascending 2 for Desc Const xlYes = 1 Set objExcel = CreateObject(“Excel.Application”)’Create the excel object objExcel.Visible = True’Make excel visible Set objWorkbook = _ objExcel.Workbooks.Open(“C:\Jay\Docs1.xls”)’Open the document Set objWorksheet = objWorkbook.Worksheets(1)’select the sheet based on the index .. 1,2 ,3 … Set objRange = objWorksheet.UsedRange’which select the range of the cells has some data other than blank Set objRange2 = objExcel.Range

How to Read or Select Context Menu or Right Click Menu using QTP.

Select The Item in Right Click Menu or Context Menu: Window("sampleWindow").WinMenu("MenuObjType:=1).Select"File;New" Here MenuObjtype can be 1 r 2 r 3 .......n Check wether the Item is Exist or Not: If Window("sampleWindow").WinMenu("MenuObjType:=1).GetItemProperty("1","Exist") Then   Msgbox"Exist" Else  Msgbox"Does Not Exist" End If                                         Or If Window("sampleWindow").WinMenu("MenuObjType:=1).GetItemProperty("File","Exist") Then   Msgbox"Exist" Else  Msgbox"Does Not Exist" End If Get the Items in Context Menu: For i = 1 to 10 Print  Window("sampleWindow").WinMenu("MenuObjType:=" & i).GetItemProperty("1","Label") Then Next

How to Download a file using VbScript

Following is the code to download a file using Vbscript, without using QTP This code uses the HTMLDom and URLDownloadToFile method from urlmon API. Since VBScript does support calling Native API methods directly, here I am using  Excel macro to declare a function for the urlmon API and running the macro by Excel API from VBscript Step1: Create a new excel and open the visual basic editor, Insert Module and paste the following code the Module, save the excel file Private Declare Function URLDownloadToFile Lib “urlmon” Alias _                                            “URLDownloadToFileA” ( _                                            ByVal pCaller As Long, ByVal szURL As String, _                                            ByVal szFileName As String, _                                            ByVal dwReserved As Long, _                                            ByVal lpfnCB As Long) As Long Sub FileSave(strUrl, Des)     r = URLDownloadToFile(0, strUrl, Des, 0, a)