我以这种方式有一堆原始数据:
Parent | Data
---------------
Root | AAA
AAA | BBB
AAA | CCC
AAA | DDD
BBB | EEE
BBB | FFF
CCC | GGG
DDD | HHH
这需要转化成一棵像时装一样的树。 这基本上需要以 Excel 电子表格形式结束。 如何将上述数据转换为以下数据:
AAA | |
| BBB |
| | EEE
| | FFF
| CCC |
| | GGG
| DDD |
| | HHH
有没有简单的方法可以仅使用 VBA 来完成此操作?
最佳答案
我确信您可以整理它,但这适用于您提供的数据集。
开始之前,您需要定义两个名称(插入/名称/定义)。 “数据”是数据集的范围,“目的地”是您希望树到达的位置。
Sub MakeTree()
Dim r As Integer
' Iterate through the range, looking for the Root
For r = 1 To Range("Data").Rows.Count
If Range("Data").Cells(r, 1) = "Root" Then
DrawNode Range("Data").Cells(r, 2), 0, 0
End If
Next
End Sub
Sub DrawNode(ByRef header As String, ByRef row As Integer, ByRef depth As Integer)
'The DrawNode routine draws the current node, and all child nodes.
' First we draw the header text:
Cells(Range("Destination").row + row, Range("Destination").Column + depth) = header
Dim r As Integer
'Then loop through, looking for instances of that text
For r = 1 To Range("Data").Rows.Count
If Range("Data").Cells(r, 1) = header Then
'Bang! We've found one! Then call itself to see if there are any child nodes
row = row + 1
DrawNode Range("Data").Cells(r, 2), row, depth + 1
End If
Next
End Sub
关于vba - 在 Excel 中构建类似树的数据表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1074004/