【问题标题】:Creating an excel hierarchy创建 Excel 层次结构
【发布时间】:2021-05-28 20:17:09
【问题描述】:

我正在尝试从大型数据源(数千个条目)在 excel 中创建层次结构,并且我正在尝试创建一个可以转换我的数据集的宏。

我尝试转换的数据示例(不是真实数据):

但是,我需要以下两种格式之一:

示例 1:

示例 2(首选):

我对 excel 宏世界真的很陌生,希望能得到一些帮助。

【问题讨论】:

标签: excel vba excel-formula


【解决方案1】:

只需使用选项 Outline 做一个数据透视表:

Design the layout and format of a PivotTable

将所有字段放入行部分。

这就是你所需要的。它将完全满足您对第一张图片的要求。

更新:默认情况下,数据透视表按 A-Z 排序。但是您可以自定义拖动每个选项的排序,因此Road会出现在Subway之后。

【讨论】:

  • 非常感谢!
【解决方案2】:

如果您不想要数据透视表,可以使用以下代码将数据读入字典树结构。

这可用于生成所需的输出:

Option Explicit

Public Sub Example()
    ' read data into array
    Dim Data() As Variant
    Data = Range("A2:G6").Value
    
    ' create a tree
    Dim RootTree As Object
    Set RootTree = CreateObject("Scripting.Dictionary")
    
    ' fill tree with data
    Dim iRow As Long
    For iRow = LBound(Data, 1) To UBound(Data, 1)
        Dim Parent As Object
        Set Parent = RootTree
        
        Dim iCol As Long
        For iCol = LBound(Data, 2) To UBound(Data, 2)
            If Not Parent.Exists(Data(iRow, iCol)) Then
                Parent.Add Data(iRow, iCol), CreateObject("Scripting.Dictionary")
            End If
            Set Parent = Parent(Data(iRow, iCol))
        Next iCol
    Next iRow
    
    ' output tree
    PrintTree RootTree
End Sub

Private Sub PrintTree(ByVal Tree As Object, Optional ByVal Level As Long = 0)
    Dim Key As Variant
    For Each Key In Tree.Keys
        Debug.Print String(Level * 2, " ") & Key
        If VarType(Tree(Key)) = 9 Then
            PrintTree Tree(Key), Level + 1
        End If
    Next
End Sub

例如从这个数据中

它会产生以下输出

USA
  City
    New York
      Subway
        Singal
          V1.1
            SIG-0004
            SIG-0005
        Access point
          AP(11/04)
            AP-12
      Road
        Singal
          V4.2
            SIG-0034
            SIG-0035

对于在单元格中输出,您可以使用

Private Sub OutputTree(ByVal Tree As Object, ByVal StartOutput As Range, Optional ByVal Level As Long = 0)
    Static iRow As Long
    
    Dim Key As Variant
    For Each Key In Tree.Keys
        StartOutput.Offset(RowOffset:=iRow, ColumnOffset:=Level).Value = Key
        iRow = iRow + 1
        If VarType(Tree(Key)) = 9 Then
            OutputTree Tree(Key), StartOutput, Level + 1
        End If
    Next
End Sub

然后这样称呼它

OutputTree RootTree, ThisWorkbook.Worksheet("Output").Range("A1")

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    相关资源
    最近更新 更多