根据Excel中的预定义级别(公式或VBA)创建层次结构

时间:2017-01-20 11:49:46

标签: excel vba formula hierarchy

以下是我当前的Excel表格:

enter image description here

我想自动生成黄色的第三列,作为所有活动的分层视图。我尝试用公式解决这个挑战,但我不确定这是最好的方法。

有人已经面临并在Excel中解决了这个问题吗?有什么建议/建议可以指导我吗?

非常感谢和最诚挚的问候!

1 个答案:

答案 0 :(得分:0)

您可以将此宏粘贴到工作表的代码模块中,然后从那里运行它:

Sub CalculateHierarchy()

    Dim rLevels As Range, rLevel As Range
    Dim level As Integer, maxLevels As Integer, cur As Integer, i As Integer
    Dim h As String, counts() As Integer

    Set rLevels = Range("A2:A" & Range("A1").End(xlDown).Row)
    maxLevels = WorksheetFunction.Max(rLevels)
    ReDim counts(1 To maxLevels)

    cur = 1
    For Each rLevel In rLevels
        level = rLevel.Value
        If level > cur + 1 Then
            rLevel.Activate
            MsgBox "error at row " & rLevel.Row & " level increase by more than 1"
            Exit Sub
        End If

        h = ""
        counts(level) = counts(level) + 1
        For i = 1 To level
            h = h & "." & counts(i)
        Next
        h = Mid(h, 2)
        For i = level + 1 To UBound(counts)
            counts(i) = 0
        Next
        rLevel.Offset(, 2).Value = h
        cur = level
    Next
    rLevel.Offset(0, 2).Interior.ColorIndex = 6
End Sub