本帖最后由 一把小刀闯天下 于 2018-9-6 21:51 编辑
'C列可以为空,因为关系确定后层级也就确定了
Option Explicit
Sub Test()
Dim arr, i, j, k, n, brr(), t, cnt, m, tt
arr = [b2:d8]
For i = 1 To UBound(arr, 1)
If arr(i, 3) = "无" Then
n = n + 1
ReDim Preserve brr(1 To n)
brr(n) = arr(i, 1)
End If
Next
ReDim crr(1 To Rows.Count, 1 To 2): n = 0
For i = 1 To UBound(brr)
n = n + 1: cnt = 1
crr(n, 1) = brr(i) & "-1"
For j = 1 To UBound(arr, 1)
cnt = 2
If arr(j, 3) = brr(i) Then
crr(n, 1) = crr(n, 1) & "|" & arr(j, 1) & "-" & cnt
Call rec(arr, arr(j, 1), crr, n, cnt + 1)
End If
Next j, i
cnt = 0: ReDim arr(1 To Rows.Count, 1 To 2)
For i = 1 To n
If InStr(crr(i, 1), "|") Then
t = Split(crr(i, 1), "|")
For j = 0 To UBound(t)
m = m + 1
For k = j + 1 To UBound(t)
If Split(t(j), "-")(1) = Split(t(k), "-")(1) Then Exit For
Next
tt = Split(t(j), "-")
arr(m, 1) = Space(4 * (tt(1) - 1)) & tt(0) & "(" & tt(1) & "级)"
If j <> 0 And k = UBound(t) + 1 Then arr(m, 2) = 1 Else arr(m, 2) = k - j
Next
Else
m = m + 1
tt = Split(crr(i, 1), "-")
arr(m, 1) = tt(0) & "(1级)": arr(m, 2) = 1
End If
Next
[j:k].ClearContents
[j2].Resize(m, 2) = arr
End Sub
Function rec(arr, s, crr, n, cnt)
Dim i
For i = 1 To UBound(arr, 1)
If arr(i, 3) = s Then
crr(n, 1) = crr(n, 1) & "|" & arr(i, 1) & "-" & cnt
Call rec(arr, arr(i, 1), crr, n, cnt)
End If
Next
End Function |