Excel VBA根据2个变量重新排序行

时间:2016-03-10 22:01:43

标签: excel vba excel-vba loops

我试图从大多数高级订单中订购一份基于经理人员的员工名单。棘手的部分是让所有高级员工上市,然后再转到同一级别的下一个人。例如,请看这个图片:

What I am looking to achieve

所有向Dick直接或间接报告的人都会被列在他的下方,然后再转到彼得 - 他的下一个人。

所以如果表格如下:

What I am trying to sort

是否有一个VBA会重新排序表,看起来像第一个例子?要重新排序的表可能看起来不像这样 - 无论是谁错误地订购了它都必须工作。

注意:同一级别的人的顺序并不重要......

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我喜欢这样的东西。创建一个包含两个选项卡的Excel工作表,并命名一个“输入”和一个“输出”。将示例表复制到“输入”,然后将标题复制到“输出”。然后插入下面的代码。这应该向您展示这个基本递归的想法。在VBA中做起来相当可怕,在C中它会更漂亮。

Option Explicit

Dim RawName() As Variant
Dim RawManager() As Variant
Dim RawLevel() As Variant
Dim TopNode As Integer

Sub FncSortHierarchy()

    TopNode = FncPopulateRawHierarchy("A", "B", "C")

    If TopNode <> 0 Then

        Sheets("Output").Select
        FncWritePerson (TopNode)
        FncGetSubordinates (TopNode)

    End If

End Sub

Private Function FncGetSubordinates(indexManager As Integer) As Integer

    Dim i As Integer
    Dim name As String
    Dim manager As String

    manager = RawName(indexManager)

    For i = 1 To UBound(RawName)

        If RawManager(i) = manager Then

            name = RawName(i)
            FncWritePerson (i)
            FncGetSubordinates (i)

        End If

    Next i

End Function

Private Function FncWritePerson(index As Integer)

    Dim nextRow As Integer

    nextRow = ActiveSheet.UsedRange.Rows.Count + 1

    Range("A" & nextRow) = RawName(index)
    Range("B" & nextRow) = RawManager(index)
    Range("C" & nextRow) = RawLevel(index)

End Function

Private Function FncPopulateRawHierarchy(nameCol As String, managerCol As String, levelCol As String) As Integer

    Dim i As Integer

    Sheets("Input").Select
    ReDim RawName(ActiveSheet.UsedRange.Rows.Count)
    ReDim RawManager(ActiveSheet.UsedRange.Rows.Count)
    ReDim RawLevel(ActiveSheet.UsedRange.Rows.Count)

    For i = 2 To ActiveSheet.UsedRange.Rows.Count

        RawName(i - 1) = Range(nameCol & i).Value
        RawManager(i - 1) = Range(managerCol & i).Value
        RawLevel(i - 1) = Range(levelCol & i).Value

        If RawManager(i - 1) = "N/A" Then FncPopulateRawHierarchy = i - 1

    Next i

End Function