Function ABC_RANK(number, ref, Optional order)
Dim i As Integer, j As Integer
Dim pos As Integer
Dim swap1, swap2
Dim Items As New Collection
On Error Resume Next
For i = 1 To ref.Rows.Count
Items.Add ref.Cells(i, 1), CStr(ref.Cells(i, 1).Value)
Next i
On Error GoTo 0
' Sort the unique list
For i = 1 To Items.Count - 1
For j = i + 1 To Items.Count
If Items(i) > Items(j) Then
swap1 = Items(i)
swap2 = Items(j)
Items.Add swap1, before:=j
Items.Add swap2, before:=i
Items.Remove i + 1
Items.Remove j + 1
End If
Next j
Next i
' Rank in ascending or descending order?
If IsMissing(order) Then LastArg = 0 Else LastArg = order
If LastArg = 0 Then
pos = Items.Count
Inc = -1
Else
pos = 1
Inc = 1
End If
' Find the position of number in the sorted list
For i = 1 To Items.Count
If number = Items(i) Then
ABC_RANK = pos
Exit Function
End If
pos = pos + Inc
Next i
End Function