本帖最后由 一把小刀闯天下 于 2018-12-25 15:19 编辑
Option Explicit
Sub test()
Dim arr, i, j, k, a, b, cnt, m, n, s, t, dic
Set dic = CreateObject("scripting.dictionary")
arr = [a1].CurrentRegion.Offset(1)
ReDim brr(1 To UBound(arr, 1), 1 To 10 + 2) '最多支持10级
arr(UBound(arr, 1), 1) = "成品料号"
ReDim crr(1 To 100) As String
For i = 2 To UBound(arr, 1) - 1
For j = i To UBound(arr, 1) - 1
If arr(j + 1, 1) = "成品料号" Then
t = arr(i, 2): cnt = 1
For k = i + 1 To j
If arr(k, 2) = arr(i, 2) Then cnt = cnt + 1
Next
For k = 1 To cnt
For a = i To j
If arr(a, 2) = t Then
arr(a, 2) = vbNullString
s = arr(a, 3)
Call rec(arr, i, j, arr(a, 3), s)
m = m + 1: n = 2
brr(m, 1) = t: s = Split(s, ",")
dic.RemoveAll
For b = 0 To UBound(s)
n = n + 1: brr(m, n) = s(b)
dic(s(b)) = dic(s(b)) + 1
If dic(s(b)) > 1 Then brr(m, 2) = "互为父子:" & s(b)
Next
End If
Next a, k
i = j: Exit For
End If
Next j, i
With [e3]
.Resize(Rows.Count - 2, UBound(brr, 2)).ClearContents
.Resize(m, UBound(brr, 2)) = brr
End With
End Sub
Function rec(arr, a, b, t, s)
Dim i, j
For i = a To b
If arr(i, 2) = t Then
s = s & "," & arr(i, 3)
arr(i, 2) = vbNullString
Call rec(arr, a, b, arr(i, 3), s)
End If
Next
End Function
|