Option Explicit
Sub test1()
Dim ar(), br(), cr$(), i&, j&, n&, dic As Object, vKey
Application.ScreenUpdating = False
Set dic = CreateObject("Scripting.Dictionary")
ar = Sheets(2).[a1].CurrentRegion.Value
For i = 2 To UBound(ar)
vKey = ar(i, 2)
dic(vKey) = dic(vKey) & " " & i
Next i
For Each vKey In dic.keys
cr = Split(dic(vKey))
If UBound(cr) > 1 Then
ReDim br(1 To UBound(cr), 1 To UBound(ar, 2))
For i = 1 To UBound(cr)
For j = 1 To UBound(ar, 2)
br(i, j) = ar(cr(i), j)
Next j
Next i
qsort br, 1, UBound(br), 1, UBound(br, 2)
dic(vKey) = br
Else
dic.Remove vKey
End If
Next
With [a1].CurrentRegion
.Offset(1, 3).Clear
ar = .Value
For i = 2 To UBound(ar)
vKey = ar(i, 2)
If dic.exists(vKey) Then
n = 3
br = dic(vKey)
For j = 2 To UBound(br)
n = n + 1
ar(i, n) = br(j, 1) - br(j - 1, 1)
Next j
End If
.Value = ar
Next i
End With
Set dic = Nothing
Application.ScreenUpdating = True
Beep
End Sub
Function qsort(ByRef ar, ByVal iFirst&, ByVal iLast&, ByVal iLeft&, _
ByVal iRight, Optional ByVal iKey& = 1, Optional isOrder As Boolean = True)
Dim i&, j&, k&, vTemp1, vTemp2
i = iFirst: j = iLast: vTemp1 = ar((iFirst + iLast) / 2, iKey)
While i <= j
If isOrder Then
While ar(i, iKey) < vTemp1: i = i + 1: Wend
While vTemp1 < ar(j, iKey): j = j - 1: Wend
Else
While ar(i, iKey) > vTemp1: i = i + 1: Wend
While vTemp1 > ar(j, iKey): j = j - 1: Wend
End If
If i <= j Then
For k = iLeft To iRight
vTemp2 = ar(i, k): ar(i, k) = ar(j, k): ar(j, k) = vTemp2
Next
i = i + 1: j = j - 1
End If
Wend
If iFirst < j Then qsort ar, iFirst, j, iLeft, iRight, iKey, isOrder
If i < iLast Then qsort ar, i, iLast, iLeft, iRight, iKey, isOrder
End Function
|