How to remove duplicated items in an array.
This is (in my opinion) a very fast way of doing it.
I don't know of any faster methods.
If you need to remove duplicated items from an array of a different type, then just adjust the code accordingly.
Note: You will need to add a reference to "Microsoft Scripting Runtime" as the code uses its Dictionary object.
To do this, select Project from the toolbar, then select "References", and then select "Microsoft Scripting Runtime"
VB Code:
Option Explicit Private Sub removeDuplicates(ByRef arrName() As Long) Dim i As Long, tempArr() As Long: ReDim tempArr(UBound(arrName)) Dim d As New Dictionary, n As Long For i = 0 To UBound(arrName) If Not d.Exists(arrName(i)) Then d.Add arrName(i), arrName(i) tempArr(n) = arrName(i): n = n + 1 End If Next ReDim Preserve tempArr(n) arrName = tempArr End Sub Private Sub Form_Load() Dim x() As Long, i As Long: ReDim x(99) '' this loop will fill the array with values : '' 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3... '' For i = 0 To 99 x(i) = i Mod 4 Next '' now remove the duplicated items '' removeDuplicates x '' now display whats left For i = 0 To UBound(x) - 1 Debug.Print i & ":" & x(i) Next End Sub




Reply With Quote