31)How to compare two excel files and
highlight the cells with different values in the first file?
Excel object is being created here
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
Two files sac1 and sac2 are opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Set WB_Obj_2= Exl_Obj.Workbooks.Open("C:\sac2.xls")
Cells in the first sheet of both the files are compared
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Set WS_Obj_2= WB_Obj_2.Worksheets(1)
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
Two files sac1 and sac2 are opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Set WB_Obj_2= Exl_Obj.Workbooks.Open("C:\sac2.xls")
Cells in the first sheet of both the files are compared
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Set WS_Obj_2= WB_Obj_2.Worksheets(1)
For Each cell In WS_Obj_1.UsedRange
If cell.Value <> WS_Obj_2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 6
Else
cell.Interior.ColorIndex = 0
End If
Next
Exl_Obj.workbooks("sac1.xls").save
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.workbooks("sac2.xls").save
Exl_Obj.workbooks("sac2.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.workbooks("sac2.xls").save
Exl_Obj.workbooks("sac2.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
32) How to compare two excel sheets of the same excel workbook and
highlight the cells with different values in the first sheet?
Excel object is being created here
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
File sac1 is being opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Cells in the first and second sheet of sac1 are compared
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Set WS_Obj_2= WB_Obj_1.Worksheets(2)
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
File sac1 is being opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Cells in the first and second sheet of sac1 are compared
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Set WS_Obj_2= WB_Obj_1.Worksheets(2)
For Each cell In WS_Obj_1.UsedRange
If cell.Value <> WS_Obj_2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 6
Else
cell.Interior.ColorIndex = 0
End If
Next
Exl_Obj.workbooks("sac1.xls").save
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
33) How to compare two different ranges in a same sheet of excel
workbook and highlight the cells with different values in the first range?
I assume here that the count of cells in both the ranges is equal
e.g. these two ranges – B6:B38 and F6:F38 have equal number of cells in between
them.
myrange=inputbox("enter range of cells e.g. A1:A5")
myrange1=inputbox("enter range of cells e.g. B1:B5")
Excel object is being created here
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
File sac1 is being opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Declaring and setting a range object
set rr1=WB_Obj_1.Worksheets(1).range(myrange)
set rr2=WB_Obj_1.Worksheets(1).range(myrange1)
myrange=inputbox("enter range of cells e.g. A1:A5")
myrange1=inputbox("enter range of cells e.g. B1:B5")
Excel object is being created here
Set Exl_Obj = CreateObject("Excel.Application")
Exl_Obj.Visible = True
File sac1 is being opened
Set WB_Obj_1= Exl_Obj.Workbooks.Open("C:\sac1.xls")
Set WS_Obj_1= WB_Obj_1.Worksheets(1)
Declaring and setting a range object
set rr1=WB_Obj_1.Worksheets(1).range(myrange)
set rr2=WB_Obj_1.Worksheets(1).range(myrange1)
With rr1
lr1 = .Rows.Count
lc1 = .Columns.Count
End With
With rr2
lr2 = .Rows.Count
lc2 = .Columns.Count
End With
for i= 1 to lr1
for j=1 to lc1
if (rr1.cells(i, j).value)<> (rr2.cells(i, j).value) then
rr1.cells(i, j).Interior.ColorIndex = 6
end if
next
next
Exl_Obj.workbooks("sac1.xls").save
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
Exl_Obj.workbooks("sac1.xls").close
Exl_Obj.Application.Quit
set Exl_Obj=nothing
34) How to compare two files in QTP?
Public Function CompareFiles (F_Path_1, F_Path_2)
Dim FS, first_file, second_file
Set FS = CreateObject("Scripting.FileSystemObject")
'Function will simply exit if the size of both files being
compared is not equal
If FS.GetFile(F_Path_1).Size <> FS.GetFile(F_Path_2).Size Then
CompareFiles = True
Exit Function
End If
'OpenAsTextStream Method: Opens a specified file and returns
a TextStream object that can be used to read from, write to,
or append to the file.
Set first_file = FS.GetFile(F_Path_1).OpenAsTextStream(1, 0)
Set second_file = FS.GetFile(F_Path_2).OpenAsTextStream(1, 0)
CompareFiles = False
'AtEndOfStream Property: Read-only property that returns True
if the file pointer is at the end of a TextStream file; False
if it is not.
Do While first_file.AtEndOfStream = False
'The Read method reads a specified number of characters from
a TextStream file
Str1 = first_file.Read(1000)
Str2 = second_file.Read(1000)
'The StrComp function compares two strings and returns 0 if
the strings are equal
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop
first_file.Close()
second_file.Close()
End Function
File1 =inputbox ("Enter first file name e.g. C:\Readme1.pdf")
File2 = inputbox ("Enter second file name e.g. C:\Readme2.pdf")
If CompareFiles(File1, File2) = False Then
MsgBox File1 & " and " & File2 & " " & "are identical."
Else
MsgBox File1 & " and " & File2 & " " & "are NOT identical."
End If
35)How to search in a text file using regular expression?
I have text file like below and I want to search all words which
start with “Pass” and have number at the end. I have chosen this simple regular
expression pattern in order to make you understand. You can choose any other
simple or complex pattern you want to use.

Const ForReading = 1
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "Pass[0-9]"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Test.txt", ForReading)

Const ForReading = 1
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "Pass[0-9]"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Test.txt", ForReading)
Do Until objFile.AtEndOfStream
strSearchString = objFile.ReadLine
Set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
For Each strMatch in colMatches
msgbox strSearchString
Next
End If
Loop
Image Tool Tip
'Works fine for an image on http://www.google.co.in/, make sure that www.google.co.in is open in IE and then run the below two lines in QTP.
b=Browser("name:=Google").Page("title:=Google").WebElement("outertext:=India", "height:=110").Object.title
msgbox b

Link Tool Tip
'You have to place mouse manually over the link after clicking on Run in QTP as shown in the below screenshot - works on http://www.yahoo.com/
Browser("name:=Yahoo!").Page("title:=Yahoo!").Link("name:=My Yahoo!").mouseover
wait(1)
ttip =Window("nativeclass:=tooltips_class32").GetROProperty("text")
Msgbox ttip

Link Tool Tip
'Works fine on http://in.yahoo.com/?p=us for link named All Yahoo! Services.
ttip=Browser("name:=Yahoo! India").Page("title:=Yahoo! India").Link("name:=All Yahoo! Services").Object.title
msgbox ttip

Image Tool Tip
'Works fine on http://www.google.com/ for image, make sure google.com is open and run the below two lines in QTP
ttip=Browser("name:=Google").Page("title:=Google").Image("src:=http://www.google.com/intl/en_ALL/images/logo.gif").getROProperty("alt")
msgbox ttip

Search Box Tool Tip
'Works fine on http://www.google.com/ for search text box, make sure that google is open in IE and run the below two lines in QTP.
ttip=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Object.title
msgbox ttip

WordPad Toolbar Icon Tool Tip
'Works fine on Wordpad, you DO NOT need to place the mouse manually. It tells you the tooltip of the New icon on toolbar below the File menu. Make sure that a WordPad is open and run the below lines in QTP.
Window("text:=Document - WordPad").WinToolbar("text:=Standard").MouseMove 5, 20
wait(1)
ttip =Window("nativeclass:=tooltips_class32").GetROProperty("text")
Msgbox ttip

'Works fine for an image on http://www.google.co.in/, make sure that www.google.co.in is open in IE and then run the below two lines in QTP.
b=Browser("name:=Google").Page("title:=Google").WebElement("outertext:=India", "height:=110").Object.title
msgbox b

Link Tool Tip
'You have to place mouse manually over the link after clicking on Run in QTP as shown in the below screenshot - works on http://www.yahoo.com/
Browser("name:=Yahoo!").Page("title:=Yahoo!").Link("name:=My Yahoo!").mouseover
wait(1)
ttip =Window("nativeclass:=tooltips_class32").GetROProperty("text")
Msgbox ttip

Link Tool Tip
'Works fine on http://in.yahoo.com/?p=us for link named All Yahoo! Services.
ttip=Browser("name:=Yahoo! India").Page("title:=Yahoo! India").Link("name:=All Yahoo! Services").Object.title
msgbox ttip

Image Tool Tip
'Works fine on http://www.google.com/ for image, make sure google.com is open and run the below two lines in QTP
ttip=Browser("name:=Google").Page("title:=Google").Image("src:=http://www.google.com/intl/en_ALL/images/logo.gif").getROProperty("alt")
msgbox ttip

Search Box Tool Tip
'Works fine on http://www.google.com/ for search text box, make sure that google is open in IE and run the below two lines in QTP.
ttip=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Object.title
msgbox ttip

WordPad Toolbar Icon Tool Tip
'Works fine on Wordpad, you DO NOT need to place the mouse manually. It tells you the tooltip of the New icon on toolbar below the File menu. Make sure that a WordPad is open and run the below lines in QTP.
Window("text:=Document - WordPad").WinToolbar("text:=Standard").MouseMove 5, 20
wait(1)
ttip =Window("nativeclass:=tooltips_class32").GetROProperty("text")
Msgbox ttip

37) Using ADO connection & SQL Query to extract specific rows
from an excel sheet.
You can use plain excel script or ADO. If you need to extract all
the information from the excel sheet than plain old excel script would do fine,
but if you need to extract some specific information then ADO can be used as
below: The below code runs the query which shows only the Failed rows in a
message box.
The excel file as below is located at C:\sac.xls

below two lines determine how (and if) a recordset can be updated.
'Recordsets can be set to read-only, or they can be configured
'to allow updates. For most scripts, the LockType can be set to
'adLockOptimistic (value = 3). With this setting, the record being
'edited is not locked (that is, no restrictions are placed on another
'user accessing that record) until you call the Update method.
'adCmdText indicates that the command is a SQLstatement
Const adLockOptimistic = 3
Const adCmdText = &H0001
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
'below just remember to give the location of your xls file
'HDR=Yes indicates that our spreadsheet has a header row and
'the provider will not include the first row of the cell range (which may
'be a header row) in the RecordSet.
The excel file as below is located at C:\sac.xls

below two lines determine how (and if) a recordset can be updated.
'Recordsets can be set to read-only, or they can be configured
'to allow updates. For most scripts, the LockType can be set to
'adLockOptimistic (value = 3). With this setting, the record being
'edited is not locked (that is, no restrictions are placed on another
'user accessing that record) until you call the Update method.
'adCmdText indicates that the command is a SQLstatement
Const adLockOptimistic = 3
Const adCmdText = &H0001
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
'below just remember to give the location of your xls file
'HDR=Yes indicates that our spreadsheet has a header row and
'the provider will not include the first row of the cell range (which may
'be a header row) in the RecordSet.
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\sac.xls;" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
objRecordset.Open "Select * FROM [Sheet1$] where Result = 'Fail'", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
a= objRecordset.Fields.Item("Scenario No")
b=objRecordset.Fields.Item("Scenario Text")
c=objRecordset.Fields.Item("Result")
msgbox (a &" "&b&" "& c)
objRecordset.MoveNext
Loop
38) A script to open, display and close a PDF file using QTP.
Below is just a simple example which shows how to open a PDF file,
show it on the screen and close it. I have a PDF QTP_PAM.pdf in my c:\ drive.
Option Explicit
Dim accapp, acavdocu
Dim pdf_path
pdf_path = "C:\QTP_PAM.pdf"
'AcroExch.App is the Acrobat application; below we are initializing Acrobat by creating App object
Set accapp = CreateObject( "AcroExch.App" )
'show method shows the Acrobat application
accapp.Show()
'we have to create one AVDoc object per displayed document
Set acavdocu = CreateObject( "AcroExch.AVDoc" )
'open the PDF
acavdocu.Open pdf_path, "MyTitle"
wait 0, 200
accapp.CloseAllDocs()
accapp.Exit()
Set accapp = Nothing : Set acavdocu = Nothing
Option Explicit
Dim accapp, acavdocu
Dim pdf_path
pdf_path = "C:\QTP_PAM.pdf"
'AcroExch.App is the Acrobat application; below we are initializing Acrobat by creating App object
Set accapp = CreateObject( "AcroExch.App" )
'show method shows the Acrobat application
accapp.Show()
'we have to create one AVDoc object per displayed document
Set acavdocu = CreateObject( "AcroExch.AVDoc" )
'open the PDF
acavdocu.Open pdf_path, "MyTitle"
wait 0, 200
accapp.CloseAllDocs()
accapp.Exit()
Set accapp = Nothing : Set acavdocu = Nothing
39) A script to search for a particular text in a PDF file using
QTP.
Below code searches for text “Windows” in a PDF file. You can
learn more about method FindText and Wait which are used in this code here and here.
Option Explicit
Dim accapp, acavdocu
Dim pdf_path, bReset, Wrd_count
pdf_path = "C:\Tips.pdf"
'AcroExch.App is the Acrobat application; below we are initializing Acrobat by creating App object
Set accapp = CreateObject( "AcroExch.App" )
'show method shows the Acrobat application
accapp.Show()
'we have to create one AVDoc object per displayed document
Set acavdocu = CreateObject( "AcroExch.AVDoc" )
' opening the PDF
Option Explicit
Dim accapp, acavdocu
Dim pdf_path, bReset, Wrd_count
pdf_path = "C:\Tips.pdf"
'AcroExch.App is the Acrobat application; below we are initializing Acrobat by creating App object
Set accapp = CreateObject( "AcroExch.App" )
'show method shows the Acrobat application
accapp.Show()
'we have to create one AVDoc object per displayed document
Set acavdocu = CreateObject( "AcroExch.AVDoc" )
' opening the PDF
If acavdocu.Open( pdf_path, "" ) Then
acavdocu.BringToFront()
bReset = 1 : Wrd_count = 0
'FindText:Finds the specified text, scrolls so that it is visible, and highlights it
Do While acavdocu.FindText( "Primary", 1, 1, bReset )
bReset = 0 : Wrd_count = Wrd_count + 1
Wait 0, 200
Loop
End If
accapp.CloseAllDocs()
accapp.Exit()
msgbox "The word 'Windows' was found " & Wrd_count & " times."
Set accapp = Nothing:Set accapp = Nothing
The above code when run shows a message box like this below:

40) How to get first 3 words of first page of any PDF file using
QTP.
strFileName = "C:\Readme.pdf"
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
For i = 0 To AcroPDDoc.GetNumPages - AcroPDDoc.GetNumPages
' AcquirePage: Acquires the specified page. The first page in a PDDoc is always 0. returns true if
successful and false otherwise.
Set PageNumber = AcroPDDoc.AcquirePage(i)
'the Hilite list object is being created
Set PageText = CreateObject("AcroExch.HiliteList")
PageText.Add 0, 3 ' getting 3 words of first page.
'text selection AcroTextSelect is being created
Set AcroTextSelect = PageNumber.CreateWordHilite(PageText)
'GetNumText: Gets the number of text elements in a text selection. Use this method to determine
how many times to call the PDTextSelect.GetText method to obtain all of a text selection’s text.
For j = 0 To AcroTextSelect.GetNumText -1
PText = PText & AcroTextSelect.GetText(j)
Next
Next
msgbox PText
AcroAVDoc.Close True
AcroApp.Exit
Set AcroDoc = Nothing
Set AcroApp = Nothing
41) How to highlight first word of first page of any PDF file
using QTP.
gPDFPath = "C:\Tips.pdf"
'AcroExch.App object allows you to control Acrobat
set gApp = CreateObject("AcroExch.App")
gApp.Show()
'AcroExch.AVDoc: creates an object to manipulate the actual PDF document
set gAvDoc = CreateObject("AcroExch.AVDoc")
gAvDoc.Open gPDFPath,""
'GetAVPageView returns AcroExch.AVPageView and AcroExch.AVPageView is an area of the Acrobat application’s window that displays the contents of a document’s page.
set acroPageView = gAvDoc.GetAVPageView()
acroPageView.GoTo(0)' goes to the first page which is there on opening the document
'the Hilite list object is being created
set ourhitlist = CreateObject("AcroExch.HiliteList")
ourhitlist.Add 0, 1 'starting from 0 offset and first word
set d_page = acroPageView.GetPage()
set Select_text = d_page.CreateWordHilite(ourhitlist)
gAvDoc.Settextselection(Select_text)
wait 5
gAvDoc.Showtextselect()
gAvDoc.Close(True)
'AcroExch.App object allows you to control Acrobat
set gApp = CreateObject("AcroExch.App")
gApp.Show()
'AcroExch.AVDoc: creates an object to manipulate the actual PDF document
set gAvDoc = CreateObject("AcroExch.AVDoc")
gAvDoc.Open gPDFPath,""
'GetAVPageView returns AcroExch.AVPageView and AcroExch.AVPageView is an area of the Acrobat application’s window that displays the contents of a document’s page.
set acroPageView = gAvDoc.GetAVPageView()
acroPageView.GoTo(0)' goes to the first page which is there on opening the document
'the Hilite list object is being created
set ourhitlist = CreateObject("AcroExch.HiliteList")
ourhitlist.Add 0, 1 'starting from 0 offset and first word
set d_page = acroPageView.GetPage()
set Select_text = d_page.CreateWordHilite(ourhitlist)
gAvDoc.Settextselection(Select_text)
wait 5
gAvDoc.Showtextselect()
gAvDoc.Close(True)
42) Reading data from PDF and writing to a text file using QTP.
'Reading for example first three word of the first page of
abc2.pdf and writing to r.txt.
strFileName = "C:\abc2.pdf"
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
strFileName = "C:\abc2.pdf"
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
For i = 0 To AcroPDDoc.GetNumPages - AcroPDDoc.GetNumPages
' AcquirePage: Acquires the specified page. The first page in a PDDoc is always 0. returns true if
successful and false otherwise.
Set PageNumber = AcroPDDoc.AcquirePage(i)
'the Hilite list object is being created
Set PageContent = CreateObject("AcroExch.HiliteList")
PageContent.Add 0, 20 ' getting 3 words of first page.
'text selection AcroTextSelect is being created
Set AcroTextSelect = PageNumber.CreateWordHilite(PageContent)
'GetNumText: Gets the number of text elements in a text selection. Use this method to
determine how many times to call the PDTextSelect.GetText method to obtain all of a text selection’s text.
For j = 0 To AcroTextSelect.GetNumText -1
Content = Content & AcroTextSelect.GetText(j)
Next
Next
msgbox Content
strFile = "c:\r.txt"
strText = Content
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile (strFile, ForAppending, True)
objTextFile.WriteLine(strText)
objTextFile.Close
AcroAVDoc.Close True
AcroApp.Exit
Set AcroDoc = Nothing
Set AcroApp = Nothing
43) Combining two PDF files into one file using QTP.
Here I am combining abc.pdf and abc1.pdf to New_File.pdf
Set AcroPDDoc = CreateObject("AcroExch.PDDoc")
Set PDDoc = CreateObject("AcroExch.PDDoc")
'source file from which we will take few pages
b = PDDoc.Open("c:\abc.pdf")
'destination file at the end of which we will insert pages. Although in the last line instead of New_File.pdf you can give abc1.pdf, but I have given a new file name to avoid any confusion.
b = AcroPDDoc.Open("c:\abc1.pdf")
'22: number of pages in the destination file -1
'PDDoc: LPDISPATCH argument for the source document.
'LPDISPATCH is a typedef for a pointer to an IDispatch and IDispatch is the interface that exposes the 'OLE Automation protocol.
'0: The first page of source to be inserted into the destination document.
'1: number of pages to insert
'False: Whether Bookmarks are to be copied or not.
b = AcroPDDoc.InsertPages(22, PDDoc, 0, 1, False)
'saving combined pages to new file, you can choose the destination file also.
b = AcroPDDoc.Save(1, "c:\New_File.pdf")
Set AcroPDDoc = CreateObject("AcroExch.PDDoc")
Set PDDoc = CreateObject("AcroExch.PDDoc")
'source file from which we will take few pages
b = PDDoc.Open("c:\abc.pdf")
'destination file at the end of which we will insert pages. Although in the last line instead of New_File.pdf you can give abc1.pdf, but I have given a new file name to avoid any confusion.
b = AcroPDDoc.Open("c:\abc1.pdf")
'22: number of pages in the destination file -1
'PDDoc: LPDISPATCH argument for the source document.
'LPDISPATCH is a typedef for a pointer to an IDispatch and IDispatch is the interface that exposes the 'OLE Automation protocol.
'0: The first page of source to be inserted into the destination document.
'1: number of pages to insert
'False: Whether Bookmarks are to be copied or not.
b = AcroPDDoc.InsertPages(22, PDDoc, 0, 1, False)
'saving combined pages to new file, you can choose the destination file also.
b = AcroPDDoc.Save(1, "c:\New_File.pdf")
44) How to crop a PDF file using QTP.
'Here I am cropping a PDF file named abc.pdf and after cropping it
saving it as tt.pdf. While cropping a PDF file make sure you keep left and
bottom values as 0 as shown in the code below. For more understanding see the
screenshots below.
strFileName = "C:\abc.pdf"
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
For i = 0 To AcroPDDoc.GetNumPages - AcroPDDoc.GetNumPages
Set PageNumber = AcroPDDoc.AcquirePage(i)
Set acropoint = PageNumber.GetSize()
msgbox acropoint.y
Set rect = CreateObject("AcroExch.Rect")
rect.Left = 0
rect.Right = 612
rect.Top = 720 'it was 792 originally
rect.Bottom = 0
a=PageNumber.CropPage(rect)
Next
b = AcroPDDoc.save (1,"C:\tt.pdf")
AcroPDDoc.close
AcroAVDoc.Close True
AcroApp.Exit
Set AcroDoc = Nothing
Set AcroApp = Nothing
Also See:
Acrobatusers
Example:
As you can see below, initially the values for right and top coordinates are 8.50 and 11.00 (Inches) or (612 X 792 Points) respectively. If you want to see the dimensions (top, right, left, bottom) in Points instead of Inches, follow the below steps in section "How to check coordinates in Points instead of Inches?"

Below is the screenshot after cropping the file by giving the values to rect.right as 612 and to rect.top as 700 in the code above:

How to check coordinates in Points instead of Inches?
Open any PDF document and click on Pages on the left side.

Right click on any page and select Crop Pages...

Crop Pages dialog box opens. From the Units dropdown select Points.

On the right hand side you will see the dimensions in Points.

strFileName = "C:\abc.pdf"
Set AcroApp = CreateObject("AcroExch.App")
AcroApp.Show
Set AcroAVDoc = CreateObject("AcroExch.AVDoc")
AcroAVDoc.Open strFileName,""
Set AcroAVDoc = AcroApp.GetActiveDoc
Set AcroPDDoc = AcroAVDoc.GetPDDoc
For i = 0 To AcroPDDoc.GetNumPages - AcroPDDoc.GetNumPages
Set PageNumber = AcroPDDoc.AcquirePage(i)
Set acropoint = PageNumber.GetSize()
msgbox acropoint.y
Set rect = CreateObject("AcroExch.Rect")
rect.Left = 0
rect.Right = 612
rect.Top = 720 'it was 792 originally
rect.Bottom = 0
a=PageNumber.CropPage(rect)
Next
b = AcroPDDoc.save (1,"C:\tt.pdf")
AcroPDDoc.close
AcroAVDoc.Close True
AcroApp.Exit
Set AcroDoc = Nothing
Set AcroApp = Nothing
Also See:
Acrobatusers
Example:
As you can see below, initially the values for right and top coordinates are 8.50 and 11.00 (Inches) or (612 X 792 Points) respectively. If you want to see the dimensions (top, right, left, bottom) in Points instead of Inches, follow the below steps in section "How to check coordinates in Points instead of Inches?"

Below is the screenshot after cropping the file by giving the values to rect.right as 612 and to rect.top as 700 in the code above:

How to check coordinates in Points instead of Inches?
Open any PDF document and click on Pages on the left side.

Right click on any page and select Crop Pages...

Crop Pages dialog box opens. From the Units dropdown select Points.

On the right hand side you will see the dimensions in Points.

45) QTP & SQL-Server Database Connection
The below QTP script shows a simple example of connecting QTP with SQL Server. For the
purpose of this example I have created a simple table with three columns as
shown below. The QTP script here is showing the values of second column in the
message box one by one. In the below script do not forget to use your own
server, username, password, database etc.




Option Explicit
Dim con,rs
'The ADO Connection Object is used to create an open connection to a data source.
Set con=createobject("adodb.connection")
'The ADO Recordset object is used to hold a set of records from a database table.
'A Recordset object consist of records and columns (fields). When you first open a Recordset,
'the current record pointer will point to the first record and the BOF and EOF properties are False.
'If there are no records, the BOF and EOF property are True.
Set rs=createobject("adodb.recordset")
'Below it shows provider, server, username, password, database
con.open"provider=sqloledb.1;server=server2008;uid=rts_dev1;pwd=password;database=model"
'See all the parameters to recordset "Open" command - http://www.w3schools.com/ado/met_rs_open.asp
rs.open"select * from person",con
Do while not rs.eof
'will show the SECOND column values
msgbox rs.fields.Item(1)
rs.MoveNext
Loop
con.Close
46) QTP Script to Count Elements on a Webpage

I have used www.google.com on Firefox 3.0.13 for this script (See above screenshot). Make sure google.com is open in Firefox. Write the below script in a new test in QTP and run it.
L=0
W=0
m=0
WB=0
Set oDesc = Description.Create()
'You can use the ChildObjects method to retrieve all objects located inside a
'specified parent object, or only those child objects that fit a certain programmatic description.
Set rc = Browser("name:=Google").Page("title:=Google").ChildObjects(oDesc)
num = rc.Count()
For i=0 to num-1
'checking whether the object is a Link or Image etc.
var = rc(i).GetTOProperty("Class Name")
Select Case var
Case "Link"
L=L+1
var2 = rc(i).GetROProperty("text")
c=c & var2 & vbcrlf
Case "Image"
m=m+1
var1 = rc(i).GetROProperty("src")
b=b & var1 & vbcrlf
Case "WebElement"
W=W+1
Case "WebButton"
WB=WB+1
Case Else
End Select
Next
msgbox "Links "& L & vbcrlf &"Images "& m & vbcrlf & "WebElements " & W & vbcrlf & "WebButtons " & WB
msgbox b
msgbox c
The line with ChildObjects method in the script retrieves all the objects on this google page. And from all the retrieved objects, you can find out whether the object is a Link or Image etc. Furthermore you can retrieve different properties of those retrieved objects. The above script when run shows these below message boxes. The first message box contains objects and their count. The second contains the path of the retrieved images. In this case it shows only 1 path as only 1 image was retrieved. In the next message box it shows value of “text” property for all the links retrieved. In this way you can modify the script according to your requirements.



47) QTP Script to show the name of the Inbox folder in the message
box.

A very simple four line example to show the name of the Inbox folder in the message box. For this example make sure that Microsoft Outlook is open (I have used Outlook 2007). Write the below code in a new test in QTP and run it. It will show a message box with “Inbox” written in it.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'GetDefaultFolder - Returns a MAPIFolder object that represents the default
'folder of the requested type for the current profile
Set MyFolder = olns.GetDefaultFolder(6)
msgbox MyFolder.name
See most commonly used folder types:
olFolderDeletedItems = 3
olFolderOutbox = 4
olFolderSentMail = 5
olFolderInbox = 6
olFolderCalendar = 9
olFolderContacts =10
olFolderJournal = 11
olFolderNotes = 12
olFolderTasks = 13
olFolderDrafts = 16
48) QTP Script to count the number of mails in a given folder.
Another simple example to count the
number of mails in a given (Deleted Items) folder. For me as you can see in the
above screenshot it shows 10 in the message box. For this example make sure
that Microsoft Outlook is open (I have used Outlook 2007). Write the below code
in a new test in QTP and run it.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data issupported in Outlook, MAPI data (Messaging Application Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'GetDefaultFolder - Returns a MAPIFolder object that represents the default folder of the requested type for the current profile
Set MyFolder = olns.GetDefaultFolder(3)
msgbox MyFolder.Items.Count
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data issupported in Outlook, MAPI data (Messaging Application Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'GetDefaultFolder - Returns a MAPIFolder object that represents the default folder of the requested type for the current profile
Set MyFolder = olns.GetDefaultFolder(3)
msgbox MyFolder.Items.Count
49) QTP Script to enumerate all folders in Microsoft Outlook


Enumerating all the folders in the outlook. For this example make sure that Microsoft Outlook is open (I have used Outlook 2007). Write the below code in a new test in QTP and run it. As you can see above it shows all the folders and its subfolders in a message box. You can also compare it with the Outlook screenshot.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
For each F in olns.folders
FL = FL & F.Name & vbcrlf
For each SF in F.folders
FL = FL & " " & SF.Name & vbcrlf
Next
Next
msgbox FL
50) QTP Script to send email from Microsoft Outlook
The below script opens Outlook, sends an email message and closes
Outlook. (I have used Outlook 2007). Write the below code in a new test in QTP
and run it. Do not forget to write your email address below.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'logging into outlook application and displaying it
olns.Logon
Set objFolder = olns.GetDefaultFolder(6)
objFolder.Display
'below we are creating a new email message, assigning a recipient, subject etc. and sending it.
Set msg = olApp.CreateItem(olMailItem)
Set Recpt = msg.Recipients.Add("sachin@gmail.com")
msg.Subject = "Test Subject"
msg.body = "Test Body"
msg.send
'waiting for some time till the Outlook sends the message before closing it. Needed if network is slow.
Wait(30)
olApp.quit
If during running of the script you receive a message box like this

Then Go to Help (menu) -> Privacy Options
Go to Programmatic Access...
Select "Never warn me about suspicious activity" radio button.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'logging into outlook application and displaying it
olns.Logon
Set objFolder = olns.GetDefaultFolder(6)
objFolder.Display
'below we are creating a new email message, assigning a recipient, subject etc. and sending it.
Set msg = olApp.CreateItem(olMailItem)
Set Recpt = msg.Recipients.Add("sachin@gmail.com")
msg.Subject = "Test Subject"
msg.body = "Test Body"
msg.send
'waiting for some time till the Outlook sends the message before closing it. Needed if network is slow.
Wait(30)
olApp.quit
If during running of the script you receive a message box like this

Then Go to Help (menu) -> Privacy Options
Go to Programmatic Access...
Select "Never warn me about suspicious activity" radio button.
51) QTP Script to send an email with attachments.
Sending an email with attachments:
The below script opens Outlook, sends an email message with attachment and closes Outlook. (I have used Outlook 2007). Write the below code in a new test in QTP and run it.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'logging into outlook application and displaying it
olns.Logon
Set objFolder = olns.GetDefaultFolder(6)
objFolder.Display
'below we are creating a new email message, assigning a recipient, subject etc. and sending it.
Set msg = olApp.CreateItem(olMailItem)
Set Recpt = msg.Recipients.Add("sachin@gmail.com")
msg.Subject = "Test Subject"
msg.body = "Test Body"
msg.attachments.add "C:\r.txt" ‘more on this http://msdn.microsoft.com/en-us/library/aa179041(office.10).aspx
msg.send
'waiting for some time till the Outlook sends the message before closing it. Needed if Outlook is slow.
Wait(30)
olApp.quit
The below script opens Outlook, sends an email message with attachment and closes Outlook. (I have used Outlook 2007). Write the below code in a new test in QTP and run it.
'using the CreateObject method to create an Outlook Application object.
Set olApp = CreateObject("Outlook.Application")
'GetNameSpace - Returns a NameSpace object of the specified type. It exists because outlook was designed to be usable with different kinds of data, each of which would be identified by its own namespace. So far, only one kind of data is supported in Outlook, MAPI data (Messaging Applicaiton Programming Interface).
Set olns = olApp.GetNameSpace("MAPI")
'logging into outlook application and displaying it
olns.Logon
Set objFolder = olns.GetDefaultFolder(6)
objFolder.Display
'below we are creating a new email message, assigning a recipient, subject etc. and sending it.
Set msg = olApp.CreateItem(olMailItem)
Set Recpt = msg.Recipients.Add("sachin@gmail.com")
msg.Subject = "Test Subject"
msg.body = "Test Body"
msg.attachments.add "C:\r.txt" ‘more on this http://msdn.microsoft.com/en-us/library/aa179041(office.10).aspx
msg.send
'waiting for some time till the Outlook sends the message before closing it. Needed if Outlook is slow.
Wait(30)
olApp.quit
52)
No comments:
Post a Comment