如果您不想要数据透视表,可以使用以下代码将数据读入字典树结构。
这可用于生成所需的输出:
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")