vba - 在 Excel 中构建类似树的数据表示形式?

标签 vba treeview excel tree

我以这种方式有一堆原始数据:

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/

相关文章:

vba - 后期装订 wdGoToBookmark

mysql - 保留所有有重复项的记录并获取每个重复项的最低 id

Excel - 如何通过使用函数实现使用 "Ctrl+End"的等效结果

c# - 阅读文本段落,使用 StreamReader 获取下一行

WPF TreeView HierarchicalDataTemplate - 绑定(bind)到具有不同子集合的对象

c# - 在 WPF 中更改 BitMapImage 的尺寸,我可以在 <Image> 元素中放置什么样的对象?

Excel过滤掉名字

Excel ActiveX 组合框显示上一个值问题

excel - 如果 VBA 中出现错误?

vba - "ThisWorksheet"等效?