Eval Function & Execute Statement

by Anshoo Arora ON April 21, 2010 · Posted In All, QTP, VBScript · 45 comments

This topic covers the concepts of the Eval function and Execute statement in depth. The function Eval is used to evaluate a string and return the result of the string expression. The Execute statement on the other hand, executes one or more statements in a string expression and enables creation of dynamic code. Multiple statements can be executed at once by using colons or line breaks to separate them.

If you have had a chance to use RelevantCodes[1]One and went over the function libraries, you would find that all the events are controlled through Execute statement – data is retrieved from the Excel Table and parsed by the function libraries into string statements. Once parsed, these string statements are then executed in the same manner as QTP code.

Eval Syntax
Eval(expression)
Execute Syntax
Execute statement

Difference between Eval & Execute

In the syntax above, both expression and statement arguments are string statements. Both expressions can be derived from VBScript or QTP code; the difference lies in the fact that Eval will always return the result of the string evaluation whereas Execute will execute a string statement for execution and will not retrieve the result (but there are workarounds). The following example demonstrates the main difference between the 2 functions:

x = 9
y = 10
 
bIsEqual = Eval("x = y")
Execute "x = y"
 
MsgBox "bIsEqual: " & bIsEqual
MsgBox "X is no longer 9. It is: " & x
bIsEqual

Eval Function

New x

Execute Statement

Note that Eval returned a Boolean value whereas Execute function performed a variable assignment. This article will cover the usage of both techniques in depth through both VBS and QTP code.

You must be wondering why the syntax for Eval and Execute is different. The reason is that, Eval is a function. Execute is not. That means, the following statement for Eval: bIsEqual = Eval("x = y"), when written for Execute will return a Null value for bResult (but assignment will be performed for x):

bResult = Execute("x = y")
MsgBox bResult
MsgBox "x: " & x
Null Output

Null Output

Value Assigned

X = 10

With that said, let me share the workaround that can be used with Execute to return the evaluation just like we did with Eval. Here’s how:

x = 9
y = 10
 
Execute "z = (x = y)"
MsgBox "z: " & z
Return Z (False)

Return Z (False)

More on this concept will be covered in the section Evaluating Statements.

Creating Variables

Let’s assume a scenario where you need to create the following variables: var_1, … , var_5. One way is to manually create the variables:

var_1 = 1 : var_2 = 2 : var_3 = 3 : var_4 = 4: var_5 = 5

A quicker, and more dynamic way to achieve the same is through Execute statement:

For ix = 1 to 5
    Execute "var_" & ix & " = " & ix
Next

Option Explicit

Using the Execute statement also has a direct impact if the Option Explicit statement is ON. If a variable is not explicitly declared, an error will be occurred:

Option Explicit
 
iNumber = 9

When the same variable is created through Execute, the error will not occur and the variable will be created and value assigned successfully.

Option Explicit
 
Execute "iNumber = 9"

Evaluating Statements

Instead of equating variables and values, we will evaluate statements using Eval. A quick example using IsObject is demonstrated below:

Set dicObject = CreateObject("Scripting.Dictionary")
 
If Eval("IsObject(dicObject)") Then
    MsgBox "Object created."
    Set dicObject = Nothing
End If

Similarly, the above code can be broken into a Select Case block and variables can be evaluated by their type:

Sub RetType(ByVal var)
	Select Case Eval("TypeName(var)")
		Case "Integer" : MsgBox "Integer"
		Case "Dictionary" : MsgBox "Dictionary"
		Case "Nothing" : MsgBox "Nothing"
		Case "String" : MsgBox "String"
	End Select
End Sub
 
Call RetType(Nothing)
Call RetType("Test")
Call RetType(CreateObject("Scripting.Dictionary"))
Call RetType(1)

Upon execution, the following results will be retrieved:

Nothing

RetType(Nothing)

String

RetType('Test')

Dictionary

RetType(CreateObject)

Integer

RetType(1)

The same function above can be written through Execute. However, with Execute, we cannot directly retrieve the result (it is not a function, unlike Eval). Therefore, we will create a variable and store the result with the variable; the variable will then be used as the Select Case condition.

Sub RetType(ByVal var)
	Dim bResult
 
	Execute "bResult = TypeName(var)"
 
	Select Case bResult
		Case "Integer" : MsgBox "Integer"
		Case "Dictionary" : MsgBox "Dictionary"
		Case "Nothing" : MsgBox "Nothing"
		Case "String" : MsgBox "String"
	End Select
End Sub
 
Call RetType(Nothing)
Call RetType("Test")
Call RetType(CreateObject("Scripting.Dictionary"))
Call RetType(1)

In short then, with Execute, bResult is represented within the string statement:

Execute "bResult = TypeName(var)"

With Eval, bResult is an actual variable that holds the result like below:

bResult = Eval("TypeName(var)")

Creating Functions

I have seen this approach rarely used, but its important to know all the possibilities nonetheless. Yes, we can create Functions (really!) at run-time, as long as everything is a string and new lines are separated by colons or a line feed. This approach is generally fine for small functions, but it can get really confusing and hard to debug as the lines of code increase.

sFunc = "Function ExecuteTest"
sFunc = sFunc & vbLf
sFunc = sFunc & "MsgBox ""ExecuteTest executed."""
sFunc = sFunc & vbLf
sFunc = sFunc & "End Function"
 
Execute sFunc
 
Call ExecuteTest()

We can write the same code above using colons (:) as well:

Execute "Function ExecuteTest : MsgBox ""ExecuteTest executed."" : End Function"
 
Call ExecuteTest()

Executing QTP Statements

This is where the Execute statement absolutely shines. As stated before, RelevantCodes[1]One executes all keywords through Execute statement. It retrieves keywords from the Excel Table as strings at runtime, creates the relevant hierarchies, and executes the hierarchies with chosen events. The concept here and the concepts covered by previous examples will remain the same: we create action strings and execute them. The last example in this topic will show how different strings can be joined together to implement events on supplied test-objects (as strings).

Let’s start with a quick example to check if our target browser exists:

strBrowser = "Browser(""title:=Google"")"
 
Execute "MsgBox " & strBrowser & ".Exist(0)"

The above code can also be written with Eval as well, enabling us to retrieve the value directly instead of using the workaround approach if we were to use Execute:

strBrowser = "Browser(""title:=Google"")"
 
bExist = Eval(strBrowser & ".Exist(0)")

The above statement when executed does the same operation as it would when you would verify the browser existence using an inline DP statement: Msgbox Browser("title:=Google").Exist(0). Let’s consider another example where we create an event on a WebEdit object by creating an object hierarchy through strings at run time.

strBrowser = "Browser(""title:=Google"")"  'Browser("title:=Google")
strPage    = "Page(""title:=Google"")"     'Page("title:=Google")
strText    = "WebEdit(""name:=q"")"        'WebEdit("name:=q")
strEvent   = "Set ""Execute Test"""        'Set "Execute Test"

Execute strBrowser & "." & strPage & "." & strText & "." & strEvent

It does look interesting, doesn’t it? The same approach can be used if you are using Object Repository instead of Descriptive Programming; simply replace the Programmatic Descriptions with the Logical Descriptions in your OR, parse everything in a string and Execute it!

The example below shows how QTP code can be executed into succession through strings. The last 4 statements show how all strings are combined together to 1. Enter the search terms, 2. Click Search Button, 3. Synchronize and 4. Navigate back to the Google search page.

strBrowser = "Browser(""title:=.*Google.*"")"      'Browser("title:=Google")
strPage    = "Page(""title:=.*Google.*"")"         'Page("title:=Google")
strText    = "WebEdit(""name:=q"")"                'WebEdit("name:=q")
strButton  = "WebButton(""value:=Google Search"")" 'WebButton("value:=Google Search")
strEvent   = "Set ""Execute Test"""                'Set "Execute Test"
strClick   = "Click"                               'Click
strSync    = "Sync"                                'Sync
strBack    = "Back"                                'Back

Execute strBrowser & "." & strPage & "." & strText & "." & strEvent
Execute strBrowser & "." & strPage & "." & strButton & "." & strClick
Execute strBrowser & "." & strSync
Execute strBrowser & "." & strBack

The above strings are equivalent to the following QTP code:

Browser("title:=.*Google.*").Page("title:=.*Google.*").WebEdit("name:=q").Set "Execute Test"
Browser("title:=.*Google.*").Page("title:=.*Google.*").WebButton("value:=Google Search").Click
Browser("title:=.*Google.*").Sync
Browser("title:=.*Google.*").Back

Closing Remarks

I hope this article has covered most of the common (and uncommon) uses of Eval and Execute. I’m sure you’ll find areas in your framework where these 2 techniques will make things cleaner and more dynamic. If there is something I have omitted, please feel free to share it with us. I hope you guys find this article useful :)

Subscribe to Relevant Codes (by Anshoo Arora)

Hello! We're always posting interesting articles on Relevant Codes. Why not subscribe so you don't miss out?

Leave a Comment

{ 45 comments… read them below or add one }

Padma March 23, 2012 at 11:09 am

Hi Anshoo,

Can i use variable and regular expression together in descriptive programming?

Ex:Browser(“browser”).Page(“Page”).WebTable(“Table”).Link(“name:=”&MapTitle+”.*”,”text:=”& MapTitle+”.*” )

Appreciate your reply.

Thank you,
Padma

Reply

Anshoo Arora March 28, 2012 at 9:35 am

Padma: yes. All statements below are correct:

Browser("title:=" & MyTitle).Link("innertext:=.*" & MyLink & ".*").Click
Browser("title:=" & MyTitle & ".*").Link("innertext:=" & MyLink & ".*").Click

Reply

kumar January 4, 2012 at 9:55 am

how to use value of one variable i.e.from Action1 in to Action2, with out using datatable.
Please give me the solution no one is giving exact answer.
I tried by files-settings-parameters but it is not taking the values.
If try through Edit-Actions-Action Properties it is working only for the particular action, But I wanted it for next action.
Please give the exact solution.
Thank You

Reply

Anshoo Arora January 12, 2012 at 11:41 am

Kumar, you can either use a global variable or an Environment variable. A library associated with a test is available to all of the test’s actions – thus, a variable declared in the library will be accessible to all actions (global variable).

Reply

sam November 7, 2011 at 12:33 am

Hi,
I want to fetch the values from QTp results ie.name of function,reason of failure etc.Is there any way to fetch those data.Is there any other way to fetch those values?

Thanks in advance.

Reply

Anshoo Arora December 27, 2011 at 6:28 am

Sam, there is. You can parse the Res\Report\Results.xml file. However, this file is only available after the test run. With QTP 11, you can access the results file from another system even during the run session (if I’m not wrong).

Reply

Amshul srivasatava June 6, 2011 at 1:31 pm

Hi,

Your examples are very elaborate and clear on Eval and Execute.
Could you elaborate on the performance implications of below implementations:

#1 browser(“name:=google”).weblink(“name:=automation”).Click — Straight Descriptive programming in QTP
#2 strLink = The above line is passed as string
Execute(strLink) — Execute the Descriptive Programming through execute command
#3 boolRes = Eval(strLink) — Evaluates and executes the DP through Eval statement

Iam looking to find out if there will be differences in the time taken to execute the above lines. Will there be any differences at all?

Thanks,
Amshul

Reply

Anshoo Arora June 24, 2011 at 10:48 am

Amsual: Ran the following code as a test:

textbox = "Browser(""title:=.*Mercury.*"").WebEdit(""name:=userName"").Exist(0)"

tsStart = Timer
For ix = 0 to 499
	Execute "Print " & textBox
Next
tsEnd = Timer - tsStart

Print "Time taken using Execute: " & tsEnd

tsStart = Timer
For ix = 0 to 499
	Print Eval(textBox)
Next
tsEnd = Timer - tsStart

Print "Time taken using Eval: " & tsEnd

Results:

Time taken using Execute: 48.83984
Time taken using Eval: 49.84766

Reply

kishor gaur September 20, 2010 at 1:39 am

Hi anshoo,
I have read these articles. I am new to qtp. I wants your help in below topics.Kindly explain me in detail about

1) what is driver script. & how to use it.
2) Once I have created all the scripts in various actions how will I link all of them to run all together.
3) Also can you please sugges/provide an ebook which explains all the objects,all the methods(like GetRowWithCellText), properties for each method, of vbscript which can be used in qtp. I have been through many vbscripting books but they all just explains the basic concepts( like loops, variable, …) which are comman to all programming languages.

Please reply on my mail id. I would be thankful to you

Thanks & Regards,
Kishor gaur.

Reply

anurag wani September 8, 2010 at 7:05 am

thanks for your quick response Anshoo.

Following is the code I am using
login.vbs file //////////////////////////
Public Function fn_Login()
Browser(“title:=mybrow”).Page(“title:=mybrow”).WebEdit(“name:=txtUsername”).Set DataTable(“user_name”)
Browser(“title:=mybrow”).Page(“title:=mybrow”).WebEdit(“name:=txtPwd”).Set DataTable(“user_pwd”)
Browser(“title:=mybrow”).Page(“title:=mybrow”).WebButton(“name:=btnOK”).click
End Function
‘/////////////////main script code
executefile “D:\login.vbs ”
datatable.Import “D:\mytable.xls”
Call Function fn_Login() ‘// error is here
‘///////////////////////////////////////
here I think that the imported datavalues are not recognized by the code inside function. and hence I want to pass the data table object as argument for function so the values can be recognized inside the function [here I dont want to pass user_name and user_pwd field like Function fn_Login(DataTable("user_name "),DataTable("user_pwd ")) because actually I have to use/pass around 20 datavalues, I dont want to pass all 20 datavalues to function as argument but a datatable object instead so I can use the object inside the function to recognize the datatable parameter] waiting for your reply ….thanks in advance

Reply

Anshoo Arora September 8, 2010 at 8:10 am

Anurag,

Change:

Call Function fn_Login

to:

Call fn_Login

Reply

anurag wani September 3, 2010 at 7:38 am

Hi Anshoo, is there any way to pass the datatable object as function argument, actually I am facing a problem with my code that I am calling a function from .vbs and trying to access the global data datatable value inside it. but not able to do so….hence I thought if I can pass data table as argument, I need not to pass required parameters and can access them inside the function…plz help and correct if I am wrong…thanks in advance

Reply

Anshoo Arora September 3, 2010 at 7:58 am

Anurag,

Your function should be able to access values from the Global DataTable if the library is associated with the test. The value you retrieve will depend upon the iteration number. Can you share the code you used?

Reply

Kaushik August 23, 2010 at 5:07 am

Thanks Anshoo

Reply

Kaushik August 13, 2010 at 1:43 pm

Hi Anshoo,
I have a variable(say REG) declared in a function(say TCDoc)
I call the function TCDoc in my driver script. After that I want to call/use the variable(REG) as well.

Driver Script …
Call TCDoc(11,1)
msgbox REG

Function TCDoc…

REG=True

My requirement is to see True in the msgbox.
Could u tell me how to do it ?

Thanks
Kaushik

Reply

Anshoo Arora August 22, 2010 at 4:36 pm

You can use REG as a global variable:

REG = True

Function TCDoc(arg1, arg2)
   'code inside the function
   MsgBox REG
End Function

or:

Dim REG

Function TCDoc(arg1, arg2)
    REG = TRue
End Function

Call TCDoc(11, 1)
Msgbox REG

Reply

rakhi August 13, 2010 at 5:19 am

Hi Anshoo,
i want to know how to call a function in qtp? How many type we can call a function?can i call through action ?
Suppose I want to call a flight application’s agentname & pwd..
pls suggest

Reply

Anshoo Arora August 22, 2010 at 4:34 pm

Example:

Function MyName
    MyName = "Relevant Codes"
End Function

Code in QTP:

MsgBox MyName

Another example:

If MyName = "Relevant Codes" Then
    Reporter.ReportEvent micPass, "MyName", "Name is: " & MyName
End If

Reply

Srijit July 28, 2010 at 2:08 pm

Hi Anshoo,

Your article regarding Eval and Execute statement is really good. Reading your article I just remembered an old saying “If you have knowledge let others light their candle at it”.

Nice work.

I am also a big fan of Execute statement and have used it extensively in one of my Keyword based framework. But I am facing a problem with execute statement, each time QTP encounters an “execute” statement, it takes a lot of time to get executed (sometimes close to 1 min) . This has now become a major concern for me. Hope following details help.

1. QTP version: 9.2
2. Application: Dot Net Application
3. Example for Execute usage:
Case “WebEdit”
r_ExecuteStatement = arr_FieldDetails(0) & “.set ” & chr(34) & vr_TData & chr(34) ‘ where arr_FieldDetails(0) gives the path, Eg Browser’(“”).Page(“”).editbox(“”) etc
Execute vr_ExecuteStatement ‘ Slows down when the execute statement is encountered

Any ideas / suggestions that would help me out?

Thanks,
Srijit

Reply

Anshoo Arora July 30, 2010 at 8:48 am

Srijit,

What is the complete statement formed? What does r_ExecuteStatement equal to? Can you please share the entire QTP code that executes?

Reply

vk June 28, 2010 at 6:03 pm

Anshoo – In our script we are using OR. We have to click a weblink on the webpage but there can be multiple links with the same property.
How do i ensure that I always click the last link of those identical links?

Reply

Anshoo Arora June 28, 2010 at 7:45 pm

VK, try this:

Set oDesc = Description.Create
oDesc("micclass").Value = "Link"
oDesc("innertext").Value = ""  'Insert the text of your link here

iLinks = Browser("").Page("").ChildObjects(oDesc).Count - 1

Browser("").Page("").ChildObjects(oDesc)(iLinks).Click

Reply

Oleg May 28, 2010 at 7:42 am

The answer is simple:
We have to use Char (34) to get it working with strings.

sPer=resultSet(“PARAM”)
P_Val=trim(resultSet(“Val”))
Execute sPer&” = “&chr(34)&P_Val&chr(34)

Reply

Anonymous May 17, 2010 at 9:48 am

Sorry Anshoo I was out of my office

For all rows bellow I’ve the issue:
LEGAL_ENTITY_NAME LEGAL ENTITY NAME THIS
ATTENTION_TO ATTENTION TO NAME
LE_STREET_ADDR 10 Street
LE_CITY CITY
LE_COUNTRY Canada
LE_PROVINCE Ontario

And it is OK for all rows with numbers:

BUSINESS_PHONE_AREA_CODE 416
BUSINESS_PHONE_EXCHANGE 444
BUSINESS_PHONE_NUMBER 4444
BUSINESS_PHONE_EXT 1111

See print out bellow:
cnt=30
1 P_Param=q_LEGAL_ENTITY_NAME P_Val=LEGAL ENTITY NAME THIS
Assigned value=——————**
2 P_Param=q_ATTENTION_TO P_Val=ATTENTION TO NAME
Assigned value=——————**
3 P_Param=q_LE_STREET_ADDR P_Val=10 Street
Assigned value=——————**
4 P_Param=q_LE_CITY P_Val=CITY
Assigned value=——————**
5 P_Param=q_LE_COUNTRY P_Val=Canada
Assigned value=——————**
6 P_Param=q_LE_PROVINCE P_Val=Ontario
Assigned value=——————**
7 P_Param=q_BUSINESS_PHONE_AREA_CODE P_Val=416
Assigned value=——————*416*
8 P_Param=q_BUSINESS_PHONE_EXCHANGE P_Val=444
Assigned value=——————*444*
9 P_Param=q_BUSINESS_PHONE_NUMBER P_Val=4444
Assigned value=——————*4444*
10 P_Param=q_BUSINESS_PHONE_EXT P_Val=1111
Assigned value=——————*1111*
11 P_Param=q_EMAIL_ADDRESS P_Val=TEST@TEST.COM
Assigned value=——————**
12 P_Param=q_BUSINESS_OCCUPATION P_Val=occupation
Assigned value=——————**
13 P_Param=q_LE_ANNUAL_GROSS_INCOME P_Val=$25,000 – $50,000
Assigned value=——————**
14 P_Param=q_NET_LIQUID_ASSETS P_Val=10000
Assigned value=——————*10000*
15 P_Param=q_NET_FIXED_ASSETS P_Val=20000
Assigned value=——————*20000*
16 P_Param=q_CLIENT_LANGUAGE P_Val=English
Assigned value=——————**
17 P_Param=q_TEL_SERVICE_LANGUAGE P_Val=English
Assigned value=——————**
18 P_Param=q_LE_POSTALCODE P_Val=L4E4W4
Assigned value=——————**
19 P_Param=q_INSIDER_YESNO P_Val=no
Assigned value=——————**
20 P_Param=q_CONTROL_POSITION_YESNO P_Val=no
Assigned value=——————**
21 P_Param=q_MEMBER_YESNO P_Val=no
Assigned value=——————**
22 P_Param=q_TRADING_AUTH_SM_YESNO P_Val=no
Assigned value=——————**
23 P_Param=q_TRADING_AUTH_OTHER_YESNO P_Val=no
Assigned value=——————**
24 P_Param=q_SHARE_WITH_SCOTIABANK_GROUP P_Val=yes
Assigned value=——————**
25 P_Param=q_BANK_LOCATOR_TRANSIT P_Val=80002
Assigned value=——————*80002*
26 P_Param=q_BANK_TRANSIT_NUMBER P_Val=12345
Assigned value=——————*12345*
27 P_Param=q_BANK_ACCOUNT_NUMBER P_Val=123456
Assigned value=——————*123456*
28 P_Param=q_TYPE_OF_ACCOUNT P_Val=Chequing
Assigned value=——————**
29 P_Param=q_BANK_ACCOUNT_CURRENCY P_Val=CDN
Assigned value=——————**
30 P_Param=q_INITIAL_DEPOSIT_FLD_TEXT P_Val=10000
Assigned value=——————*10000*

HP sustomer suport can say nothing during 1 week.
Thay cannot understand what is going on.
So, you are the only person to help me, I hope
Regards,

Oleg

Reply

Oleg May 11, 2010 at 2:40 pm

Thanks Anshoo
But it doe’s not work for a case if a value is a string as it is in a code bellow:

Dim P_Val
Dim P_PARAM
Dim p_DataTablePath
p_DataTablePath="C:\Static_PARs.xls"

''===================================================   Get  General Parameter' values from   *.xls
'			Set Connection1 = CreateObject("ADODB.Connection")
'			With Connection1
'				.Provider = "Microsoft.Jet.OLEDB.4.0"
'				.ConnectionString = "Data Source="&p_DataTablePath&";" & _
'			"Extended Properties=Excel 8.0;"
'				.Open
'			End With
'			Set resultSet = Connection1.execute("SELECT  * from [Static_For_LE_Account_Creation$]")
'					resultSet.MoveFirst
'					Do until resultSet.EOF
'							 P_PARAM  = "q_" &Trim(resultSet("PARAM"))
'							 P_Val = resultSet("THEVal")
'
'							sPer=eval("P_PARAM")
'							print ("P_Val====="&P_Val)
'							Execute sPer&" = "&P_Val
'							resultSet.MoveNext
'					loop
'			resultSet.Close
'			Connection1.Close
''===============================================

DataTable.ImportSheet p_DataTablePath , "SecondPersonInfo" , "Action1"
cnt=DataTable.LocalSheet.GetRowCount
print ("cnt="&cnt)

For i=1 to cnt
       DataTable.SetCurrentRow(i)
       P_Param="q_"&Trim(DataTable.RawValue ("PARAM", "Action1") )
       P_Val=Trim(DataTable.RawValue ("Val", "Action1") )
	   print (i&"   P_Param="&P_Param&"     P_Val="&P_Val)
		sPer=eval("P_PARAM")
		Execute sPer&" = "&CStr(P_Val)
Next
print (" ")

With an excell like this:

PARAM	Val
LEGAL_ENTITY_NAME   	LEGAL ENTITY NAME THIS
ATTENTION_TO   	 ATTENTION TO NAME
LE_STREET_ADDR     	10 Street
LE_CITY    	 CITY
LE_COUNTRY    	Canada
LE_PROVINCE  	  Ontario
BUSINESS_PHONE_AREA_CODE     	416
BUSINESS_PHONE_EXCHANGE   	444
BUSINESS_PHONE_NUMBER    	4444
BUSINESS_PHONE_EXT   	1111

Please advice
Thanks
Oleg
om@meditaid.com

Reply

Anshoo Arora May 12, 2010 at 10:26 am

Hi Oleg,

On which line do you see this issue?

Reply

Anonymous May 3, 2010 at 4:58 am

(The Execute statement on the other hand, executes one or more statements in a string expression and enables creation of dynamic code.)

The Eval statement also creates dynamic code and it executes. For example,
(If there is a Notepad window in the object repository)

Eval “Window(” & Chr(34) & “Notepad” & Chr(34) & “).Close”
Execute “Window(” & Chr(34) & “Notepad” & Chr(34) & “).Close”

I think both will work in the same way in this scenario. Could please let me know the difference?

Reply

Anshoo Arora May 5, 2010 at 2:34 am

Eval cannot always create dynamic code. You can try creating a Function/Subroutine like we’ve done with Execute. Also, the usage for using Eval and Execute in some scenarios can differ; eg: .Set, FireEvent etc.

Eval “Window(” & Chr(34) & “Notepad” & Chr(34) & “).Close”
Execute “Window(” & Chr(34) & “Notepad” & Chr(34) & “).Close”

I think both will work in the same way in this scenario. Could please let me know the difference?

Eval will return a value, whereas Execute will not. Both actions will perform the same action, the exact same way. However, when creating such code, I always use Execute because the usage will always be the same in each scenario.

Reply

Kulamani Sahoo April 30, 2010 at 1:41 am

This is a common scenario anshoo.when people give their user name and password in yahoo/rediff/gmail log in page,the same log in name is displayed in all the pages after succesfull log in.Means if my login id is “qtpuser” the same name i.e “qtpuser” will be displayed in all screens of yahoopages.Please tell me how to keep track of that value through out the application.
Thanks in advance.

Reply

Anshoo Arora May 2, 2010 at 12:30 pm

I generally create a global variable (in the function library) and keep track of such data and modify it as per requirement. In other words, you can create a function library, associate it with your test. Once done, create the new variables in your library:

Dim sUserName
sUserName = "qtptester"

or, if you’re reading from a DataTable, or Excel:

Dim sUserName
sUserName = DataTable("UserName", dtLocalSheet)  'If DataTable

In your script, you can use this variable like below:

Browser("").Page("").WebEdit("").Set sUserName

Reply

Kulamani Sahoo April 28, 2010 at 6:56 am

Dear Anshoo
I am a big Fan of u r QTp Knowledge and the way u answer the queries and help countless people .
I went to an Interview panel some times back.
They asked me some qns which i didnt answer.
Plz help me in those.
1)suppose there is a string named “India” is there.in The display it shld display as
I
n
d
i
a
2)There is a webtable.Inside the web table a link is there.how to select that link with the given value.
waiting for u r answers.
Thanks in advance.

Reply

Anshoo Arora April 28, 2010 at 1:57 pm

#1:

sCountry = "India"

For ix = 1 to Len(sCountry)
	Print Mid(sCountry, ix, 1)
Next

#2:

sLink = "The Link"

With Browser("").Page("").WebTable("")
	iRow = .GetRowWithCellText(sLink)
	For iCol = 1 to .GetROProperty("cols")
		If InStr(1, .GetCellData(iRow, iCol), sLink) Then
			Exit For
		End If
	Next
	.ChildItem(iRow, iCol, "Link", 0).Click
End With

Reply

raja May 29, 2010 at 12:22 am

This is for 1st question, the only problem in this is to specify the array length initially with some big value (for ex 100)

sCountry = “India”
Dim arr(10)
For ix = 1 to Len(sCountry)
arr(ix-1)=mid(sCountry,ix,1)
aa=aa&vblf&arr(ix-1)
Next
msgbox aa

Reply

Kulamani Sahoo April 29, 2010 at 7:54 am

Hi Anshoo
Thanks for the reply.
#Ans 1 I have tried the same code in the system and it worked fine for me.I just wonder how we wll know that Print will work here.i have gone through so many books and site bt they never mentioned abt “Print”.while i searched for Print in qtop help also it didnt return anything.Can u send me all the Readymade functions which are most freeq. used in coding like Print so that we all will use it.
#Ans 2.
I have gone through the code and stil have some doubts in the following segments.

For iCol = 1 to .GetROProperty(“cols”)
If InStr(1, .GetCellData(iRow, iCol), sLink) Then
Exit For
End If
Next
.ChildItem(iRow, iCol, “Link”, 0).Click
Can u explain a bit in depth as i dont have much idea abt the methods(i.e GetRowWithCellText) you have used here.
Thanks a lot for your response.

Reply

AMIT SARAN August 11, 2010 at 12:57 pm

Anshoo
You retrieve row and col position and You mention 0 for index but what when we didnt knw the index and i dnt wana use object spy

Reply

Kulamani Sahoo April 29, 2010 at 9:19 am

Anshoo
as in #2 .GetROProperty(“cols”) what is cols?

Reply

Anshoo Arora April 29, 2010 at 3:14 pm

Print will only work when you’re executing this code in QTP. Its going to fail as a VBScript (.vbs) statement. All the relevant methods can be found under the QTP help file :) and I think that’s also the best source for most of the documentation that I refer to from time to time.

Reply

Anshoo Arora April 29, 2010 at 3:13 pm

Retrieves the number of columns of a WebTable.

Reply

Kulamani Sahoo April 30, 2010 at 1:34 am

Hi Anshoo
Thanks for The timely help n i understood both the answers
Kudoooooooooooo$ 2 u Anshoo

Reply

Anonymous May 5, 2010 at 5:16 am

Thank you…:-)

Reply

Anshoo Arora May 5, 2010 at 8:03 am

:)

Reply

gayathri June 23, 2010 at 2:08 am

Hi anushoo,

I have a similar issue as kulmani specified. my application is web based application and i supply login names from datatable (export into script). now how i need to check whether after successful login , the name in my databable is visible in application or not.

For eg: qtptest1 is the name of the user , my application will display as Welcome qtptest1 and soon for qtptestn users

i have written code for login of these multiple users , but need to validate the same in home page.

please help

thanks in advance.

gayathri

Reply

Anshoo Arora June 28, 2010 at 10:31 am

You can simply check for the WebElement on the page:

If Browser("").Page("").WebElement("innertext:=Welcome qtptest1.*").Exist(5) Then
	Reporter.ReportEvent micPass, "Login", "Login successful."
Else
	Reporter.ReportEvent micFail, "Login", "Login failed."
End If

Reply

Sivaram S August 3, 2010 at 5:29 am

Hi raja,
This can be rectified with the following Dynamic Array as given below.

Dim result()
sCountry = “India”
For i = 1 to Len(sCountry)
ReDim result(i)
result(i-1) = Mid(sCounty, i, 1)
results = results & result(i-1) & vbNewLine
Next
Msgbox results.

Sivaram S (yessivaram@gmail.com)

Reply

Anshoo Arora August 11, 2010 at 3:26 pm

Amit,

Index, Location and CreationTime are all Ordinal Identifiers. They cannot be calculated at design-time with the help of Object Spy. These are run-time configurations, and can only be determined when the test executes.

Also, in the code you see, if there is a only 1 image in the cell, it will have Index 0. If there are 2 images, they will share Indexes 0 and 1. It depends on the situation completely and the number of the same type of objects in a given cell.

Reply

Previous post:

Next post: