Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

Sorting string from an array

Status
Not open for further replies.

Camille1

Aerospace
Mar 25, 2005
12
0
0
US
I have a list of strings and I would like collect from that list only one time if the strings the same for example if an array("A", "B", "C", "A", "B", "B")
and I would like to collect ("A", "B", "C"). How do I do that. Thanks in advance
 
Replies continue below

Recommended for you

One way would be to put the array into a collection, since you cannot have duplicate data in a collection, only those strings not equal would be in the collection.

Regards,

Regg
 
Hi Regg,
I am kind of new to VB, I tried to collect like you suggested, can you give me sample code.
Thanks
Sub Sorting()
Dim ListString
Dim CollList As New Collection
ListString = Array("A", "B", "B", "A", "C")

i = 0
Do
CollList.Add ListString(i)
If i = UBound(ListString) Then Exit Do
i = i + 1
Loop

Debug.Print CollList.count

End Sub
 
I use a dictionary to do this
Sub GetUniqueEntries()
'note add a reference to Microsoft Scripting runtime to be able to use dictionary objects
Dim ListString, i As Integer
Dim DicList As New Dictionary
ListString = Array("A", "B", "B", "A", "C")

For i = 0 To UBound(ListString)
If DicList.Exists(ListString(i)) Then
Else
DicList.Add ListString(i), ""
End If
i = i + 1
Next
For i = 0 To DicList.Count - 1
Debug.Print DicList.Keys(i)
Next
End Sub
 
Camille1,

Sorry for taking so long to answer your reply.

What I meant was that collections do not allow duplicate keys. Try this code:

Code:
Sub Sorting()

    [COLOR=green]'declare variables[/color]
    Dim ListString As Variant
    Dim Item As Variant
    
    [COLOR=green]'create collection[/color]
    Dim CollList As New Collection
    
    [COLOR=green]'create test array[/color]
    ListString = Array("A", "B", "B", "A", "C")
    
    [COLOR=green]'set error routine to skip duplicate key[/color]
    On Error Resume Next
    
    [COLOR=green]'loop through test array[/color]
    For Each Item In ListString
    
        [COLOR=green]'add item to collect using item as both item and key[/color]
        [COLOR=green]'collections do not allow duplicate keys and raises error 457[/color]
        [COLOR=green]'On Error Resume Next lets program continue on with stopping[/color]
        CollList.Add Item, Item
        
    Next
    
    [COLOR=green]'turn off error handling[/color]
    On Error GoTo 0
    
    [COLOR=green]'display number of collection items in immediate window[/color]
    Debug.Print CollList.Count
    
End Sub

Regards,

Regg


 
Status
Not open for further replies.
Back
Top