Private Function isCollExists(coll As Collection, ByVal strKey As String) As Boolean
On Error Resume Next
With coll(strKey)
If Err.Number = 0 Then isCollExists = True Else isCollExists = False
End With
End Function
Sub Test()
Dim arr(), c As New Collection, rng As Range, i As Long, j As Long, k As Long, p As Long, v
With Sheets("Sheet2")
Set rng = .Range("A1:G" & .Cells(.Rows.Count, "A").End(xlUp).Row)
End With
With rng
arr = .Value
For i = 2 To UBound(arr, 1)
If Len(arr(i, 1)) Then
If arr(i, 5) = 0 And arr(i, 6) = 0 Then
j = i
arr(i, 7) = 1
Else
If isCollExists(c, arr(i, 1) & "|" & arr(i, 2)) Then
c.Add key:=arr(i, 3) & "|" & arr(i, 4), Item:=i
Else
c.Add key:=arr(i, 1) & "|" & arr(i, 2), Item:=i
End If
End If
End If
Next i
If j = 0 Then Exit Sub
p = 1
Do
If isCollExists(c, arr(j, 3) & "|" & arr(j, 4)) Then
k = c(arr(j, 3) & "|" & arr(j, 4))
c.Remove arr(j, 3) & "|" & arr(j, 4)
p = p + 1
arr(k, 7) = p
j = k
ElseIf isCollExists(c, arr(j, 1) & "|" & arr(j, 2)) Then
k = c(arr(j, 1) & "|" & arr(j, 2))
c.Remove arr(j, 1) & "|" & arr(j, 2)
v = arr(j, 1): arr(j, 1) = arr(j, 3): arr(j, 3) = v
v = arr(j, 2): arr(j, 2) = arr(j, 4): arr(j, 4) = v
p = p + 1
arr(k, 7) = p
j = k
Else
Exit Do
End If
Loop
.Value = arr
.Sort key1:=.Columns(7), order1:=xlAscending, header:=xlYes
.Columns(7).ClearContents
End With
End Sub
Bookmarks