Table of Contents

Frequently Asked Coding Questions During Interview on UFT

Read here also for one more interview question.

How to Add digits of a given number?

Here the trick to check if we are following mod logic to get the number. However, we can use for loop to get the numbers one by one and add them.
I have explained the mod logic as below

Dim num, sum
num=inputbox ("Enter a Four digit number")
If Len(num) = 4 Then
sum=sum+num mod 10
num= left (num, 3)
sum=sum+num mod 10
num= left (num, 2)
sum=sum+num mod 10
num= left (num, 1)
sum=sum+num mod 10
msgbox ("Sum is " &sum)
msgbox "Number, you entered is not a 4 digit number"
End If

How to read any Four-digit number and display the number in reverse order?

off course we can convert the given digit to String and use the inbuilt String reverse function.We can use recursion to solve the issue.  Here is an approach to use the aabove-writtenmod logic to reverse the same.

Dim num,rev
num= inputbox("Enter a number")
If len(num)=4 Then
rev=rev*10 + num mod 10
num= left(num,3)
rev=rev*10 + num mod 10
num= left(num,2)
rev=rev*10 + num mod 10
num= left(num,1)
rev=rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
msgbox "Number, you entered is not a 4 digit number"
End If

one more approach to reverse the number:

Dim num,n
n=Inputbox ("Enter a Vaule")
For num=n to 1 step -1
msgbox num

How to calculate the grade for an examination and display the grade obtained?

The conditions are:

  • If average marks Greater than or equal to 75, the grade is Distinction
  • If average marks Greater than or equal to 60 and less than 75 , then the grade is First
  • If average marks Greater than or equal to 50 and less than 60, then the grade is Second
  • If average marks Greater than or equal to 40 and less than 50 , then the grade is Third
  • Minimum marks 35 for any subject, otherwise ‘no grade fail’)
READ  How to Call Reusable API Script From GUI Script in UFT


There are several ways to solve this. The most efficient code is to use the Switch statement. I have coded with if else

Dim e,m,p,c, tot
e=inputbox ("Enter english Marks")
m=inputbox ("Enter maths Marks")
p=inputbox ("Enter physics Marks")
c=inputbox ("Enter chemistry Marks")
tot= cdbl(e) + cdbl(m) + cdbl(p) + cdbl(c)
msgbox tot
If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=300 Then
msgbox "Grade is Distinction"
else If cdbl(e) >=35 and cdbl(m) >=35 and cdbl(p) >=35 and cdbl(c) >=35 and tot >=240 and tot<300 Then
End if
End if

How to calculate Even or odd calculation till n(any given number)

Dim num,n
n=Inputbox ("Enter a Vaule")
For num= 1 to n step 2
msgbox num

Write a program for finding out whether the given year is a leap year or not?

Dim xyear
xyear=inputbox ("Enter Year")
If xyear mod 4=0 Then
msgbox "This is a Leap year"
msgbox "This is NOT"
End If

Read two numbers and display the sum?

Dim num1,num2, sum
num1=inputbox ("Enter num1")
num2=inputbox ("Enter num2")
sum= Cdbl (num1) + Cdbl (num2) 'if we want add two strings conversion require
msgbox ("Sum is " &sum)

How to Calculate the odd even number in UFT?

Dim num
num=inputbox ("Enter a number")
If num mod 2=0 Then
msgbox "This is a Even Number"
msgbox "This is a Odd Number"
End If


How to Calculate the Simple Interest?

Dim p,t, r, si
p=inputbox ("Enter Principle")
t=inputbox ("Enter Time")
r=inputbox ("Enter Rate of Interest")
si= (p*t*r)/100 ' p= principle amount, t=time in years, r= rate of interest
msgbox ("Simple Interest is " &si)


How to display natural numbers up to n and write in a text file?

Dim num, n, fso, myfile
n= inputbox ("Enter any Value")
For num= 1 to n step 1
Set fso= createobject ("scripting.filesystemobject")
set myfile=fso.opentextfile ("D:test.txt", 8, true)
myfile.writeline num

How to display Natural numbers summation up to n? (Using For…Next Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
For num= 1 to n step 1
sum= sum+num
msgbox sum


How to display Natural numbers sum up to n? (using While…Wend Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
While num <=cdbl (n)
sum= sum+num
msgbox sum


Display Natural numbers sum up to n? (Using Do…Until…Loop)

Dim num, n, sum
n= inputbox ("Enter a Value")
sum= sum+num
Loop Until num =cdbl (n+1)
msgbox sum

Write a Function for Natural Numbers sum up to n

Function NNumCou (n)
Dim num, sum
For num= 1 to n step 1
sum= sum+num
msgbox sum
End Function

Verify weather the entered 10 digit value is a numeric value or not

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))

If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
Msgbox "It is NOT Numeric"
End If

Slightly upgraded logic

Dim a,x,y,z,num
num=Inputbox ("Enter a Phone Number")
d1= left (num,1)
d10=Right (num,1)
d2=mid (num, 2, len (1))
d3=mid (num, 3, len (1))
d4=mid (num, 4, len (1))
d5=mid (num, 5, len (1))
d6=mid (num, 6, len (1))
d7=mid (num, 7, len (1))
d8=mid (num, 8, len (1))
d9=mid (num, 9, len (1))
If len (num) =10 Then
If isnumeric (d1) = "True" and isnumeric (d2) = "True" and isnumeric (d3) = "True" and isnumeric (d4) = "True"and isnumeric (d5) = "True"and isnumeric (d6) = "True"and isnumeric (d7) = "True"and isnumeric (d8) = "True"and isnumeric (d9) = "True"and isnumeric (d10) = "True" Then
msgbox "It is a Numeric Value"
End If
End If
If len (num) <> 10 Then
Msgbox "It is NOT valid Number "
End If


How to read a number and verify that number Range weather in between 1 to 100 or 101 to 1000?

Option explicit
Dim a,x
a=Inputbox ("Enter a Vaule")
If a<= 100 Then
For x= 1 to 100
If a=x Then
msgbox "a is in between 1 to 100 range"
End If
For x= 101 to 1000
If a=x Then
msgbox "a is in between 101 to 1000 range"
End If
End If

How to check if a given letter is present in the given String ?

Yes, the interviewer wanted to know if I knew how to use the various Vbscript functions. That is why I needed to code in this way. It is not very efficient though but showed that I knew the VBscript inbuilt functions and how to use them.

Dim x
x=Inputbox ("Enter your String")
y=Inputbox ("Enter your search character")
x2=Left (x,1)
x3=mid (x,2,Len(1))
x4=mid (x,3,Len(1))
If y=4 Then
If x1=y or x2=y or x3=y or x4=y Then
msgbox y &" is there"
msgbox y &" is Not there"
End If
msgbox "Invalid Data"
End If

How to work with MSWORD in UFT?

The below snippet will open a word document and write something and save it as test.doc

Dim MyobjWD
Set MyobjWD = CreateObject("Word.Application")
MyobjWD.Selection.TypeText "This is some text." & Chr(13) & "This is some more text"
MyobjWD.ActiveDocument.SaveAs "D:test.doc"

How to count the number of occurance of a word in a given file?


sMyString="hello world"
Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFso.OpenTextFile(sMyFileName, FOR_READING)
sReadTxt = oTxtFile.ReadAll
Set oRegEx = New RegExp
oRegEx.Pattern = sMyString
oRegEx.IgnoreCase = bIgnoreCase
oRegEx.Global = True
Set oMatches = oRegEx.Execute(sReadTxt)
MatchesFound = oMatches.Count
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound

How to Compare two test files in UFT?

Dim f1, f2
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
Str2 = File2.Read
CompareFiles = StrComp(Str1, Str2, 0)
If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
End Function
Call Comparefiles(f1,f2)
If CompareFiles(f1, f2) = False Then
MsgBox "Files are identical."
MsgBox "Files are different."
End If

How to implement Mid Function Without Using String Functions?

I tried to implement the mid function here. What I have done is
1.transfer the string to Array
2.then take the size of the array
3.k is the counter to check if it is equal to strtcut that is which position i need to cut and the length is the variable to understand till how much i need to cut.


Sub Macro1()
Call midexplained("Animesh", 2, 2)
'same as mid("Animesh",2,2)
End Sub
Function midexplained(inputq, strtcut, length)
Dim bText() As Byte
Dim j As Integer
j = 0
Dim k As Integer
k = 0
Dim a(999)
Dim n As String
Dim MyString As String: MyString = inputq
bText = MyString
For i = 0 To UBound(bText) - 1
If (bText(i) = 0) Then
a(j) = Chr(bText(i))
j = j + 1
End If
For k = 0 To UBound(a) - 1
If a(k) = "" Then
ElseIf k + 1 >= strtcut And k < ((strtcut + length) - 1) Then
n = n & a(k)
End If
MsgBox "value of n is " & trim(n)
End Function

The output for both the variable is the same.

READ  The Probable And Constraints Of Artificial Intelligence

How to Swap two number or two input strings?

sinp1=Inputbox("Enter the First string:")
sinp2=Inputbox("Enter the second string:")
msgbox scon
msgbox lensinp1
msgbox lensinp2
msgbox lenscon
'For i=1 to lenscon
'msgbox smid1
srght=right(scon, lensinp2)
msgbox "The swapped last name: " &srght
sleft=left(scon, lensinp1)
msgbox "The swapped first name: " &sleft
msgbox "The swapped string:" & scon2

How to find the Dedcimal value of a given hexadecimal and vice varsa?

sinp=Inputbox("Enter the Hexadecimal number::")
For i=1 to slen
If isnumeric(smid)=False Then
Select Case smid
Case "A" n=10
Case "B" n=11
Case "C" n=12
Case "D" n=13
Case "E" n=14
Case "F" n=15
End Select
End If
msgbox ("The Decimal Equivalentof the Hex number:: "&sinp&"=" &c)

How to find out if a string is having numeric values or not?

sinp=Inputbox("Enter the String::")
For i=1 to slen
If isnumeric(smid) Then
snum=snum & smid
End If
If tfchk=True Then
msgbox snum
End If

Design a basic calculator that takes two input and and an operation as input and provide us the result.

Option explicit
Dim x,y, Operation, Result
x= Inputbox (" Enter x value")
y= Inputbox ("Enter y value")
Operation= Inputbox ("Enter an Operation")
Select Case Operation
  Case "add"
      Result= cdbl (x)+cdbl (y)
      Msgbox "Addition of x,y values is "&Result
  Case "sub"
      Result= x-y
      Msgbox "Substraction of x,y values is "&Result
  Case "mul"
    Result= x*y
      Msgbox "Multiplication of x,y values is "&Result
  Case "div"
      Result= x/y
      Msgbox "Division of x,y values is "&Result
  Case "mod"
      Result= x mod y
      Msgbox "Mod of x,y values is "&Result
  Case "expo"
      Result= x^y
      Msgbox"Exponentation of x,y values is "&Result
  Case Else
      msgbox "Wrong Operation"
End Select

How to Resize a window in QTP/UFT?

Move: This is not exactly a resizing command
Objectname.move x,y

How to extract numbers from String?

For example :

  • If we pass “There are 40 boys “, the function should return us 40.
  • Similarly, if we pass “Ticket is confirmed and the no is 56477” to the function , it should return me 56777.

Function extract_number(msg)
Dim re, matches, item, result
Set re = New RegExp
re.pattern = "[A-Za-z -.]*(d+).*"
Set matches = re.Execute(msg)
If matches.Count > 0 Then
Set item = matches(0)
If item.SubMatches.Count > 0 Then
result = item.SubMatches(0)
result = -1
End If
result = -1
End If
extract_number = result
End Function
MsgBox extract_number("There are 40 boys")
MsgBox extract_number("Ticket is confirmed and the no is 56477")

Another way:

mystring = "The order is confirmed and its no is 567"
myLength = Len(mystring)

For i = 1 To myLength
If Asc(Mid(mystring, i, 1)) <> 32 Then
If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
myNumber = myNumber & Mid(mystring, i, 1)
End If
msgbox(“no numeric”)
End If

READ  How to Delete Cookie in VBScript?

How to Ping Other computer using VBScript?

This is a sample code on how to network with another computer. This will automatically open up the command prompt and ping to the particular machine. For combating the Network latency and delay I have used some delay in the programming too.
This is mostly applicable to the networking team and those who use com/dcom.

Set oWshShell = CreateObject("wscript.Shell")
Cmd = "ping"
Set oExec = oWshShell.Exec(Cmd)
Do While oExec.Status = 0
WScript.Sleep 60
0utput= oExec.StdOut.ReadAll
error_code = oExec.StdErr.ReadAll
MsgBox "Output: " & output & vbNewLine & vbNewLine & "Errors: " & error_code

Find out a number of occurrence of Substring within a string?


Call OSS(str,substring)
Function OSS(str,sbstring)
End Function
Exp--msgbox OSS("anianianianiani","ani")

how we can measure the time required for each component to execute in QTP?

This “TimeIt” will give us the time required to execute the particular component.This is applicable to any script along with components.

'//In the head of the script...
Dim StartTime, EndTime
StartTime = Timer
....your code
EndTime = Timer
'//In the last line of the script component...
TimeIt = EndTime - StartTime

Write a code in QTP which will close a particular opened window in Desktop. Say I said only opened Notepads needs to be closed.

Set winobj=description.Create()
Set objdesk=desktop.ChildObjects(winobj)
msgbox cntobj
msgbox cntrow
For i=1 to cntobj
If Winapp1=sdt Then
End If

Write code on calling an action say the first action will take some input and will do some operation. Now the output of Action 1 will pass to Action 2. The output of Action-2 will go to Action-3. After finishing it will come back to Action1 and give the final output.

a=inputbox("Enter a number:")
b=inputbox("Enter a number:") 
RunAction "Action2", oneIteration,isum,output 
msgbox output 
imul=Inputbox("Enter a number to multiply:") 
RunAction "Action3", oneIteration, pmul, out
//Split a string and find the length 
sinp=inputbox("Enter the Path:") 
cnt=0 For i=1 to slen 
If sms="" Then 
End If 
msgbox strsplit(cnt)

Sample Scenarios to Automate in QTP -Application: Mercury tours

Application: Mercury tours

1. Book a ticket in Mercury tours by logging with jojo and bean
2. Book ticket with credit card number expiry date as 2003, 2007, 2008 (total three test iterations)
3. Go to Itinerary and check recently booked itinerary is there with correct source and destination, date and time of booking
3. Check the functionality of cancel checked reservations with selecting a specific itinerary and without selecting. Report results accordingly.


Settings to be performed in Mercury tours application before creating the script:-

1. start server (start->programs->mercury tours->start server)
2. open mercury tours application
3. login as admin and mercury as password
4. Select Data driven popup error
5. Submit

How to get Test Path in QTP/UFT?


Set qtApp = CreateObject("QuickTest.Application") ' Create the Application objectqtpApp.Test.Location
TestLoc = qtApp.Test.Location
MsgBox TestLoc

Another way..

msgbox Environment("TestDir")

However, you need to save the test before the run. Else will give
1.not save
2.temp directory as output.

How to Send Email via VBScript?

Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
Set objMail = Nothing
End Function
Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
If (Attachment <> "") Then
End If
Set Mail = Nothing
Set ol = Nothing
End Function

How to add Defects to Quality Center from UFT/QTP/Vbscript?
Here is a sample code to Connects to Quality Center (TestDirector) from a QuickTest test and adds a bug to the database. This code was taken from here

Dim TDConnection
Set TDConnection = CreateObject("TDApiOle.TDConnection")
TDConnection.InitConnection "http://hpqc/tdbin" ' URL for the DB
TDConnection.ConnectProject "TD76","abc","xyz" ' Valid login information
If TDConnection.Connected Then
MsgBox("Connected to " + chr (13) + "Server " + TDConnection.ServerName _
+ chr (13) +"Project " + TDConnection.ProjectName )
MsgBox("Not Connected")
End If
'Get the IBugFactory
Set BugFactory = TDConnection.BugFactory
'Add a new empty bug
Set Bug = BugFactory.AddItem (Nothing)
'Fill the bug with relevant parameters
Bug.Status = "New"
Bug.Summary = "Connecting to TD"
Bug.Priority = "4-Very High" ' depends on the DB
Bug.AssignedTo = "admin" ' user that must exist in the DB's users list
Bug.DetectedBy = "admin" ' user that must exist in the DB's users list
'Post the bug to database (commit)