Click to See Complete Forum and Search --> : Sorting in VBScript
itjacky
Oct 11th, 2000, 09:10 PM
I would like to ask how can I sort an array in VBScript?
I can make sorting in Javascript : newarray = myarray.sort()
But how about VBScript?
Thank you!
Serge
Oct 12th, 2000, 11:09 AM
You can do something like this:
Sub SortArray(p_Array)
Dim i
Dim j
Dim varTemp
For i = UBound(p_Array) To LBound(p_Array) Step -1
For j = LBound(p_Array) + 1 To i
If p_Array(j - 1) > p_Array(j) Then
varTemp = p_Array(j - 1)
p_Array(j - 1) = p_Array(j)
p_Array(j) = varTemp
End If
Next
Next
End Sub
Then just call this Sub passing the array to be sorted.
itjacky
Oct 12th, 2000, 08:31 PM
Thank you Serge,
However, this function support integer only?
Serge
Oct 13th, 2000, 02:31 PM
I would have to dissagree. This sub routine will sort string as well. Here's a little example:
<HTML>
<HEAD>
<SCRIPT LANGUAGE=vbscript>
Sub LoadArrayFromList()
Dim i
Dim arrTemp()
Dim colList
Dim objOption
For i = 0 To lstList1.options.length -1
Redim Preserve arrTemp(i)
arrTemp(i) = lstList1.options(i).innerText
Next
'At this point we have an array with all list values
'now sort it
SortArray arrTemp
'After an array is sorted, populate List2 with sorted values
Set colList = lstList2.Options
For i = 0 To Ubound(arrTemp)
Set objOption = document.createElement("OPTION")
objOption.Text=arrTemp(i)
colList.options.add(objOption)
Next
End Sub
Sub SortArray(p_Array)
Dim i
Dim j
Dim varTemp
For i = UBound(p_Array) To LBound(p_Array) Step -1
For j = LBound(p_Array) + 1 To i
If p_Array(j - 1) > p_Array(j) Then
varTemp = p_Array(j - 1)
p_Array(j - 1) = p_Array(j)
p_Array(j) = varTemp
End If
Next
Next
End Sub
</SCRIPT>
</HEAD>
<BODY>
<P>*</P>
<SELECT name=lstList1 size=6 style="width: 50pt">
<OPTION>ZZZ</OPTION>
<OPTION>YYY</OPTION>
<OPTION>TTT</OPTION>
<OPTION>FFF</OPTION>
<OPTION>EEE</OPTION>
<OPTION>AAA</OPTION>
</SELECT>
<SELECT name=lstList2 size=6 style="width: 50pt">
</SELECT>
<BR><BR>
<INPUT type="button" value="Sort" name=cmdSort OnClick=LoadArrayFromList>
</BODY>
</HTML>
By pressing the button on the page, the code will create an array from the List1, then sort it, then populate List2 with sorted values.
itjacky
Oct 13th, 2000, 09:20 PM
Oh! Yes. Yes. Thank you!
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.