QuickTest Professional Knowledge Base

This knowledge base will be updated on a regular basis so please return or follow us on Twitter to be informed of regular code postings.

QTP Knowledge Base

Q: Function to export the Run-Time Data Table into QC
Use this function to export the QTP Run-Time data Table into a resource in the Resources module in Quality Center
Just pass in the Resource name that exists in QC that you want to export it in to.
NOTE: You must have QTP connected to the QC Project
The Resource must exist in the Resources module and must be of type 'Data table'
If there is already a data table stored in the resource this function will overwrite it with the exported one.

Function ExportRunTime (ResName)
	'export run time table
	DataTable.Export "c:\TestData.xls"
    
	'connect to the resources module
	Set oTDC = QCUtil.QCConnection.QCResourceFactory
	'Get a collection of all resources in module
	Set oRoot = oTDC.NewList("")
	'ensure we start with no resources
	Set oSub = Nothing
	'count the number of resources in the module
	iTotalItems = oRoot.Count
    
	'loop through until we find the one that's passed into this function
	For ItemCtr = 1 To iTotalItems
		CurItem = oRoot.Item(ItemCtr).Name
		If UCase(CurItem) = UCase(ResName) Then
			Set oSub = oRoot.Item(ItemCtr)
		End If
	Next
	Set oRoot = Nothing
	Set oTDC = Nothing
	
	If Not oSub is nothing Then
		oSub.filename = "TestData.xls"
		oSub.ResourceType = "Data table"
		oSub.post
		oSub.UploadResource "c:\", True
	End If
End Function
Q: How to get QTP to export the Run-Time Data Table
'This subroutine exports your run-time dataTable to a user specified directory, using the test name and date and time to generate a unique file name:
'As the system time and date include invalid filename characters (":" and "/") the sub splits these into elements then concatenates them back together


Sub ExportDT (DirectoryPath)
 Dim arrDate, varDate, arrTime, varTime
 
 arrDate = Split(Date,"/")
 For each element in arrDate
   varDate = varDate & element
 Next
 arrTime = Split(time,":")
 For each element in arrTime
   varTime = varTime & element
Next

DataTable.Export DirectoryPath & Environment.value("TestName") & "_" & varDate & "_" & varTime & ".xls"
End Sub
Q: How can I get QTP to maximize the web browser?
1. Whilst recording Test -> Low-Level Recording. This will switch to Low-Level recording mode.
2. Click the maximize button on the browser. A statment similar to the following should be recorded:
Window("Microsoft Internet Explorer").Maximize
You can also use the Browser FullScreen method:
' Make browser fullscreen
Browser("Browser").FullScreen
The FullScreen method displays the browser in full-screen mode. This method is applicable when running a test using Internet Explorer only. It is not supported when using Netscape.
Q: How can I check the colour of fonts used on a web page?
Set x = Browser("Welcome: Edgewords Training").Object.Document.all.tags("FONT")
msgbox x.length

For each obj in x
	myVal = obj.getattribute("color")
	If myVal = "#ff0000" Then
		msgbox "found red"
		msgbox obj.getattribute("innerText")
	End If
Next
Q: How can I set the focus to the Internet Explorer window (Activate the window)?
1. Start Recording.
2. Go to Test -> Low-Level Recording. This will switch to Low-Level recording mode.
3. Click on the title bar of Internet Explorer. A statment similar to the following should be recorded something.
Window("Microsoft Internet Explorer").Click 35,5
Q: How do I invoke a browser instance programmitically?
'Starting a web browser:
'Set the variable to "NS" for Netscape or "IE" for Internet Explorer.
Browser1 = "IE"
StartURL = "www.yahoo.com"
IF Browser1 = "IE" THEN
	set IE = CreateObject("InternetExplorer.Application") 
	IE.Visible = true
	IE.Navigate StartURL
END IF
IF Browser1 = "NS" THEN
	SystemUtil.Run "netscp6.exe", StartURL,"C:\Program Files\Netscape\Netscape 6\", ""
END IF
Q: How can I terminate all instances of Internet Explorer from QTP?
'Kill Browser Process

On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name='iexplore.exe'")
For Each objProcess in colProcess
	objProcess.Terminate()
Next
On Error Goto 0
Q: How do I check if a window exists using QTP?
if Window("Flight Reservation").Exist(60) then
	reporter.ReportEvent micPass, "Login", "Flight Window Displayed Successfully"
else
	reporter.ReportEvent micFail, "Login", "Flight Window Failed to Display"
	ExitGlobalIteration
end if
Q: How do I minimize QTP whilst running a test?
At the top of your script use:
Dim qtApp
Set qtApp = CreateObject("QuickTest.Application")
qtApp.WindowState = "Minimized" ' Minimize QTP
wait 2
qtApp.WindowState = "Normal" ' Restore QTP
wait 2
qtApp.WindowState = "Maximized" ' Maximize QTP
Set qtApp = Nothing
Q: How to send key combinations to an application using QTP?
Use the Windows Scripting SendKeys method:
1. Download and install the Windows Scripting Host, if you do not already have it.
2. Create a WScript.Shell object.
3. Activate the browser in which you want to execute the keys.
4. Use the SendKeys method to type the key combination.

Example:
' This code executes the CTRL+F key combination (search) on a browser.

' Activate browser window
Set WshShell = CreateObject("WScript.Shell") WshShell.AppActivate "Put the label of the browser"
wait(3)
WshShell.SendKeys "^f" ' The caret (^) represents the CTRL key.
wait(2)

object.SendKeys(string)
The SendKeys method will send keystroke(s) to the active window. To send a single character (for example, x), use "x" as the string argument. To send multiple characters (for example, abc), use "abc" as the string argument. You can also send special characters such as SHIFT, CTRL, and ALT, which are represented by the plus sign (+), the caret (^), and the percent sign (%), respectively. For more information on the SendKeys method and other special keys, such as the backspace or a function key, please refer to the MSDN SendKeys Method page.
Q: How do I check if a column exists is in the data table before referencing it?
on error resume next

val=DataTable("ParamName",dtGlobalSheet)

if err.number<> 0 then
	'Parameter does not exist
else 
	'Parameter exists
end if

On error Goto 0
Q: How do you kill a process using QTP?
Call KillProcess ("'Excel.exe'")

Public Sub KillProcess (strProcess)
	strComputer = "."
	Set objWMIService=GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	Set colProcess=objWMIService.ExecQuery ("Select * from Win32_Process Where Name=" & strProcess)
	For Each objProcess in colProcess
		objProcess.Terminate()
	Next
End Sub
Q: How can I search for a window or object open on the desktop?
' If you're in QTP and looking for Windows or anything at the top level of your machine.
' First create a description object for the window or object you are looking for:

Dim oDesc, oColl
Set oDesc = Description.Create()
oDesc("<property>").Value = "<value>"

' Get collection of all childObjects that match desciption
Set oColl = Desktop.ChildObjects(oDesc)

' Now you can access the object and use your standard QTP methods etc.
oColl(0).Activate
Q: How to use QTP to send an email through Outlook
Sub SendMailOutlook(aTo, Subject, TextBody, aFrom)

	'Create an Outlook object
	Dim Outlook 'As New Outlook.Application

	Set Outlook = CreateObject("Outlook.Application")

	'Create a new message
	Dim Message 'As Outlook.MailItem
	Set Message = Outlook.CreateItem(olMailItem)
	With Message
		'You can display the message To debug And see state
		'.Display

		.Subject = Subject
		.Body = TextBody
		'Set destination email address
		.Recipients.Add (aTo)
		'Set sender address If specified.
		Const olOriginator = 0
		If Len(aFrom) > 0 Then .Recipients.Add(aFrom).Type = olOriginator
			'Send the message
			.Send
	End With
End Sub
Q: How to compare two string files using QTP
CompareFiles (FilePath1, FilePath2)

FilePath1 The path to the first file to compare
FilePath2 The path to the second file to compare

Public Function CompareFiles (FilePath1, FilePath2)
	Dim FS, File1, File2
	Set FS = CreateObject("Scripting.FileSystemObject") 
	If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
		CompareFiles = True
		Exit Function
	End If 
	Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
	Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)
	CompareFiles = False
	Do While File1.AtEndOfStream = False
		Str1 = File1.Read(1000)
		Str2 = File2.Read(1000)
		CompareFiles = StrComp(Str1, Str2, 0)
		If CompareFiles <> 0 Then 
			CompareFiles = True 
			Exit Do
		End If
	Loop
	File1.Close()
	File2.Close()
End Function 

Return value:
' The function returns 0 or False if the two files are identical, otherwise True.

Example:
File1 = "C:\countries\apple1.jpg"
File2 = "C:\countries\apple3.jpg" 
If CompareFiles(File1, File2) = False Then
	MsgBox "Files are identical."
Else
	MsgBox "Files are different."
End If
Q: How to capture transaction times in QTP
' Instead of using Services.StartTransaction and Services.EndTransaction...
' You can capture timings like this:

StartTime = Timer
perform actions to be timed here...
EndTime = Timer
Reporter.ReportEvent micDone, "Time", EndTime-StartTime
Q: A Function to round to any number of decimal places
' Round <myValue> to <decimialPlaces>
' QTP round() function rounds down if previous digit is even and up if it's odd:
' Round(2.15) and Round(2.25) both return 2.2

Function trueRound(byval myValue, byval decimalPlaces)
	Dim oMath, oMode
	set oMath = DotNetFactory.CreateInstance("System.Math", "System")
	set oMode = DotNetFactory.CreateInstance("System.MidpointRounding", "System")
	trueRound=oMath.Round(myValue, decimalPlaces, oMode.AwayFromZero)
	set oMath = nothing
	set oMode = nothing
End Function
Q: How to connect to a Database through ODBC in QTP
' This example connects to the demo flight app Access Database that comes with QTP.
' The ODBC DSN entry is already set-up when the flight app is installed

' Connect to the Flight32 database
Set dbexample = CreateObject("ADODB.Connection") 
dbexample.Open("DSN=Flight32") 

' Perform a querySet 
recordset = dbexample.Execute("SELECT * from Orders") 
' Get the values from the Customer_Name column
while (NOT recordset.EOF) 
	MsgBox recordset.Fields("Customer_Name") 
	' Move to the next value in the record set
	recordset.MoveNext
wend

' Close the database connection.
dbexample.Close
Set dbexample = Nothing
Q: How do I convert the current date to U.S. format and add days to it?
' Changing format to U.S. and adding 10 days:

' Add 10 days
mydat =  DateAdd ("d", 10, Date())
' Split the date on the slash
myarr = split (mydat,"/")
' re-arrange into MM/DD/YY US format
mydat = myarr(1) & "/" & myarr(0) & "/" & right(myarr(2), 2)
msgbox mydat
Q: How do I create an array from the contents of a list box?
' This function reads a Windows list object, then returns an array of the items in the list

Public Function createListArray(ByRef oList)
	Dim listArr(), i, itemCount

	createListArray = micFail
	itemCount = oList.GetItemsCount
	ReDim listArr(itemCount-1)
	For i=0 To UBound(listArr)
		listArr(i)=oList.GetItem(i)
	Next
	createListArray = listArr
End Function
Q: How do you create a script template in QTP for all new scripts?
If you need any default Template to be loaded whenever you create a new Action, just follow these steps.
1. Start a text file in a text editor like notepad and design the template with all the statements and comments in.
2. Save the text file as ActionTemplate.mst to the QuickTest Installation Folder under the \dat folder.
i.e. C:\Program Files\HP\QuickTest Professional\dat
3. Start QTP and whenever you create new Actions, it will use the template by default.
Q: How to get QTP to Maximize itself before running a test
' Just enter this code snippet at the start of your script:

Set qtApp = CreateObject("QuickTest.Application")
qtApp.WindowState = "Maximized"
Set qtApp = Nothing
Q: How to programmitically raise a defect in QC from QTP
Set objBug = QCUtil.QCConnection.BugFactory.AddItem(Null)

objBug.Summary = "404 on View Balance"
objBug.Status = "New"
objBug.Priority = "3-High"
objBug.Field("BG_SEVERITY") = "3-High"
objBug.DetectedBy = "admin"
objBug.Field("BG_DETECTION_DATE") = Date
objBug.Field("BG_DESCRIPTION") = "Got a 404 not found when viewing balance"

objBug.Post
Q: Function to add minutes to the current time
' Pass in the number of minutes to be added e.g. MsgBox TimeAdd (20)

Function TimeAdd (mins)
	Dim varMyTime

	varMyTime = TimeValue (DateAdd ("n", mins, Now()))
	TimeAdd = Left (varMyTime, 5)
End Function
Q: Another way to close all instances of a browser
Function Close_All_Browsers ()
	Dim obj, TotalBrowsers, CreationTime, BrowserName, i

	Set obj = Description.Create()
	obj("micclass").value = "Browser"
	TotalBrowsers = Desktop.ChildObjects(obj).count
	CreationTime = "0"

	For i = 1 to TotalBrowsers
		BrowserName = Browser("CreationTime:=" & CreationTime).GetROProperty("name")
		If Instr (1,BrowserName,"Quality Center",1) > 0 Then
		CreationTime=CreationTime+1
	else
		Browser("CreationTime:=" & CreationTime).Close
	End If
	wait 1
	Next
	wait 3
End Function
Q: How to use VBScript to check case of text
strText = "Edgewords"

varTextVal = Asc (strText)

if varTextVal >= 65 AND varTextVal <= 90 Then
	msgbox "The first character is uppercase"
elseIf varTextVal >= 97 And varTextVal <= 122 Then
	msgbox "The first character is lowercase"
else
	msgbox "The first character is non alphabetical"
end if
Q: How to create a self-closing pop-up dialog

 Public Function SelfClosingMsgbox (title, content)
 	Dim WSObj,myPopup
    
 	Set WSObj = CreateObject("WScript.Shell")
 	myPopup = WSobj.popup(content, 3, title, 0) 'note that the '3' here determines length of time in seconds
    
 	Set WSObj = Nothing
 	Set myPopup = Nothing
 End Function

Q: Using the Print Utility statement for debugging a test

 'You can use the 'Print' statement in QTP to output information to
 'QTPs Print Log at Run-Time
 'This may be more useful than using the 'MsgBox' function as it does not
 'stop the test run and the log is still displayed after playback
 'Example:
 
 For i = 1 to 5
 	Print i * 2
 Next

Q: How to get QTP to capture the html source code from a web page


 ' Capture the source code:
SourceCode = Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Object.documentElement.outerHtml

 ' You can then use the File System Object to write the captured HTML to a local file:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oTextFile = oFSO.CreateTextFile("C:\SourceCode.html", True, -1)
oTextFile.Write(SourceCode)
Set oFSO = nothing
Set oTextFile = nothing

Q: How to choose a random item from a List Object


numberOfFlights = Window("Flight Reservation").Dialog("Flights Table").WinList("From").GetItemsCount
myRandomNumber = RandomNumber(0, numberOfFlights - 1)
reporter.ReportEvent micDone, "Select Flight", "Random Number Selected is " & cStr(myRandomNumber)

Window("Flight Reservation").Dialog("Flights Table").WinList("From").Select myRandomNumber
Q: How to programmatically loop through the Data Table

' If you are using the Global Worksheet as below, remember to set the Data Table iterations
' to run one iteration only in the Test Settings

datatable.ImportSheet "c:\FlightData.xls", "Sheet1", "Global"

varRows = datatable.GetRowCount

For i = 1 to  varRows

	DataTable.SetCurrentRow i

	Window("Flight Reservation").Activate
	Window("Flight Reservation").WinButton("New Order").Click
	Window("Flight Reservation").ActiveX("Date of flight").Type "121212"
	Window("Flight Reservation").WinComboBox("Fly From:").Select DataTable.Value ("flyfrom", dtGlobalSheet)
	Window("Flight Reservation").WinComboBox("Fly To:").Select DataTable.Value ("flyto", dtGlobalSheet)
	Window("Flight Reservation").WinButton("FLIGHT").Click
	Window("Flight Reservation").Dialog("Flights Table").WinButton("OK").Click
	Window("Flight Reservation").WinEdit("Name:").Set DataTable.Value ("firstname", dtGlobalSheet)
	Window("Flight Reservation").WinRadioButton("Business").Set
	Window("Flight Reservation").WinEdit("Tickets:").Set "2"
	Window("Flight Reservation").WinButton("Insert Order").Click
	Window("Flight Reservation").ActiveX("Threed Panel Control").WaitProperty "text", "Insert Done...", 10000
Next
Connect with Edgewords via LinkedIn
Follow @edgewords on Twitter
Test Your Skills in Our QTP, QC and Loadrunner QuizzesQuickTest Professional QuizQuality Center QuizLoadRunner Quiz
View Our Training Course Schedule

Client Testimonial

"The course was really good and I'm probably going to be sent on the Advanced QTP course, so hope to have you as my Course Tutor. Thanks to your good self I picked up a lot and I'm now in the process of looking to use what I learnt here in the office."