Non-Traditional Way to sort an array in QTP,Vbscript


“Is there any method to sort an array in VBScript?”

As VBScripter doesn’t have any inbuilt VBScript function to sort an array,we need to follow the same algorithm of Bubble sort,Selection sort,Quick sort etc.. we can overcome this limitations using .Net Class method.

well,if you have .NET Framework installed on your PC then you’ve won already šŸ™‚ [You need not worry for above version of QTP]

Firstly,we need to create an instance of System.Collections.ArrayList object.

Here,System.Collections.ArrayList being a .NET class used for creating dynamic arrays(again no need to worry about Redim and Preserve)

After creating arraylist object we then use the Add method to add items to our array.

Sort() method is used to sort in ascending order while i haven’t found reverse() method flexible as sort.For reversing we need to sort first and reverse it again..2 steps!

Lets start with:

'================================================
'Author:QTP Lab:a touch of madness!
'Date:23/11/2009
'Description:This function sorts an array into ascending
'            and descending order using .Net class methods.
'Function:SortArray()
'=========================================================

Function SortArray()

Dim myObj,sBf
sBf=""
Set myObj=CreateObject("System.Collections.ArrayList")
myObj.Add("Ba")
myObj.Add("R")
myObj.Add("A")
myObj.Add("Bb")
myObj.Add("S")
myObj.Add("M")
myObj.Add("D")
myObj.Add("J")
myObj.Add("Bc")
myObj.sort()
'myObj.reverse()   'Disable this line if you want to sort in an ascending order.

For each sNames in myObj
sBf=sBf&sNames&"-->"
Next
msgbox sBf,0,"Ascending order"

Set myObj=Nothing

End Function

Output:


Advertisements

4 responses to this post.

  1. Posted by santhosh on September 23, 2010 at 3:58 am

    Gud site

    Reply

  2. Posted by Tarun on April 14, 2011 at 5:41 pm

    Thanks.U made my day easy šŸ™‚

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: