2016年7月9日 星期六

[VBA] Remove duplicate items in array without using Scripting.Dictionary

P.S
If you want to sort the array in descending order, reserve the direction of the "red arrows" of the following two lines:

    While (vArray(tmpLow) < pivot And tmpLow < inHi)

and

    While (pivot < vArray(tmpHi) And tmpHi > inLow)





Private Sub abc()

    Dim s(6) As String
    Dim s2() As String
    Dim i As Integer
    Dim tmp As Integer
    Dim nItem As Long
    Dim nItem2 As Long
    s(0) = "9"
    s(1) = "9"
    s(2) = "9"
    s(3) = "8"
    s(4) = "8"
    s(5) = "7"
   
    nItem = UBound(s)
    QuickSort s, 0, nItem
   
    For i = 1 To nItem
        'MsgBox "s " & s(i)
    Next
   
    nItem2 = 1
    For i = 2 To nItem - 1
        If s(i) <> s(i - 1) Then
            nItem2 = nItem2 + 1
        End If
    Next
   
    ReDim s2(nItem2) As String
    s2(1) = s(1)
    tmp = 2
    For i = 2 To nItem
        If s(i) <> s(i - 1) Then
            s2(tmp) = s(i)
            tmp = tmp + 1
        End If
    Next
   
    For i = 1 To nItem2
        MsgBox s2(i)
    Next
   
End Sub

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)

    Dim pivot   As Variant
    Dim tmpSwap As Variant
    Dim tmpLow  As Long
    Dim tmpHi   As Long

    tmpLow = inLow
    tmpHi = inHi

    pivot = vArray((inLow + inHi) \ 2)

    While (tmpLow <= tmpHi)

    While (vArray(tmpLow) < pivot And tmpLow < inHi)
    tmpLow = tmpLow + 1
    Wend

    While (pivot < vArray(tmpHi) And tmpHi > inLow)
    tmpHi = tmpHi - 1
    Wend

    If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
    End If

    Wend

    If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
    If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi

End Sub