Sorting out alphabetically via VBScript with dictionary.

Many times, you will need to sort out search results to display them in alphabetic order. To do so, you will need a script. This will sort  the results out alphabetically via VBScript.

VBScript (Visual Basic Script) is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It allows Microsoft Windows system administrators to generate powerful tools for managing computers with error handlingsubroutines, and other advanced programming constructs. It can give the user complete control over many aspects of their computing environment. One of its features are Dictionaries.

You will frequently use a dictionary when you need to store items and recover them by name. For example, a dictionary can hold all the environment variables defined by the system or all the values associated with a registry key. However, a dictionary can only store one item for each key value. That is, dictionary keys must all be unique. You should keep this in mind when creating a new one.

To use a Dictionary that returns search results alphabetically, that is, in ABCDE format, you will need to create a function called  SortDictionary.

This article contains a demo application that illustrates how to sort out items alphabetically via VBScript with the ‘dictionary‘ object and the SortDictionary function. You will find the demo application for download at the end of this article; we also illustrate this article with an example of script that can be used for its execution.

Below is the code for the demo application at the end of the article:

'######################### Order Dictionary ##########################
Function SortDictionary(objDict,intSort)
Dim strDict()
Dim objKey
Dim strKey,strItem
Dim X,Y,Z

Z = objDict.Count

Const dictKey = 1
Const dictItem = 2

If Z > 1 Then
ReDim strDict(Z,2)
X = 0
For Each objKey In objDict
strDict(X,dictKey) = CStr(objKey)
strDict(X,dictItem) = CStr(objDict(objKey))
X = X + 1
Next

For X = 0 to (Z - 2)
For Y = X to (Z - 1)
If StrComp(strDict(X,intSort),strDict(Y,intSort),vbTextCompare) > 0 Then
strKey = strDict(X,dictKey)
strItem = strDict(X,dictItem)
strDict(X,dictKey) = strDict(Y,dictKey)
strDict(X,dictItem) = strDict(Y,dictItem)
strDict(Y,dictKey) = strKey
strDict(Y,dictItem) = strItem
End If
Next
Next

objDict.RemoveAll

For X = 0 to (Z - 1)
objDict.Add strDict(X,dictKey), strDict(X,dictItem)
Next
Set SortDictionary = objDict
End If
End Function

Related articles


Attachments:

SortingAlgorithm.zip

 

Este artigo foi útil? Was this post helpful?
Yes0
No0

Leave a Reply

Your email address will not be published.Required fields are marked *