Sub Test_SortDictKeys()
Dim i As Integer
Dim a(0 To 5) As Variant, b() As Variant
For i = 0 To 5
a(i) = i
Next i
MsgBox Join(a, vbLf), vbInformation, "Original Array: With No Dups and Sorted"
a(0) = 1 'Make a duplicate
a(5) = 4
a(4) = 5 'Make last two elements unsorted
MsgBox Join(a, vbLf), vbInformation, "With A Dup"
b() = UniqueArrayByDict(a)
MsgBox Join(b, vbLf), vbInformation, "No Dup"
QuickSort b()
MsgBox Join(b, vbLf), vbInformation, "No Dup and Sorted"
End Sub
'Early Binding method requires Reference: MicroSoft Scripting Runtime, scrrun.dll
Function UniqueArrayByDict(Array1d() As Variant, Optional compareMethod As Integer = 0) As Variant
'Dim dic As Object 'Late Binding method - Requires no Reference
'Set dic = CreateObject("Scripting.Dictionary") 'Late or Early Binding method
Dim dic As Dictionary 'Early Binding method
Set dic = New Dictionary 'Early Binding Method
Dim e As Variant
dic.CompareMode = compareMethod
'BinaryCompare=0
'TextCompare=1
'DatabaseCompare=2
For Each e In Array1d
If Not dic.Exists(e) Then dic.Add e, Nothing
Next e
UniqueArrayByDict = dic.Keys
End Function
'http://home.pacbell.net/beban/
'Copyright 2000 Alan Beban
Sub QuickSort(ByRef VA_array, Optional V_Low1, Optional V_high1)
On Error Resume Next
'Dimension variables
Dim V_Low2, V_high2, V_loop As Integer
Dim V_val1, V_val2 As Variant
'If first time, get the size of the array to sort
If IsMissing(V_Low1) Then
V_Low1 = LBound(VA_array, 1)
End If
If IsMissing(V_high1) Then
V_high1 = UBound(VA_array, 1)
End If
'Set new extremes to old extremes
V_Low2 = V_Low1
V_high2 = V_high1
'Get value of array item in middle of new extremes
V_val1 = VA_array((V_Low1 + V_high1) / 2)
'Loop for all the items in the array between the extremes
While (V_Low2 <= V_high2)
'Find the first item that is greater than the mid-point item
While (VA_array(V_Low2) < V_val1 And V_Low2 < V_high1)
V_Low2 = V_Low2 + 1
Wend
'Find the last item that is less than the mid-point item
While (VA_array(V_high2) > V_val1 And V_high2 > V_Low1)
V_high2 = V_high2 - 1
Wend
'If the new 'greater' item comes before the new 'less' item, swap them
If (V_Low2 <= V_high2) Then
V_val2 = VA_array(V_Low2)
VA_array(V_Low2) = VA_array(V_high2)
VA_array(V_high2) = V_val2
'Advance the pointers to the next item
V_Low2 = V_Low2 + 1
V_high2 = V_high2 - 1
End If
Wend
'Iterate to sort the lower half of the extremes
If (V_high2 > V_Low1) Then Call QuickSort(VA_array, V_Low1, V_high2)
'Iterate to sort the upper half of the extremes
If (V_Low2 < V_high1) Then Call QuickSort(VA_array, V_Low2, V_high1)
End Sub
Bookmarks