按组汇总的VBA宏

时间:2019-02-19 23:02:59

标签: excel vba

假设我有一个如下表: enter image description here

enter image description here

我试图通过(从到索引)计算总数,所需的输出将像上一栏中所示:  enter image description here

enter image description here

请提前告知如何在VBA宏中实现此目标!

1 个答案:

答案 0 :(得分:0)

尝试:

Option Explicit

Sub test()

    Dim Lastrow As Long, i As Long, CurrentIndex As Long, NextIndex As Long, WholeIndex As Long
    Dim CurrentKey As String, NextKey As String

    With ThisWorkbook.Worksheets("Sheet1")

        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 2 To Lastrow

            CurrentKey = .Range("B" & i).Value & "_" & .Range("C" & i).Value & "_" & .Range("D" & i).Value & "_" & .Range("E" & i).Value
            CurrentIndex = .Range("D" & i).Value
            NextKey = .Range("B" & i + 1).Value & "_" & .Range("C" & i + 1).Value & "_" & .Range("D" & i + 1).Value & "_" & .Range("E" & i + 1).Value
            NextIndex = .Range("D" & i + 1).Value

            If CurrentKey = NextKey Then
                    If WholeIndex = 0 Then
                        WholeIndex = CurrentIndex + NextIndex
                    Else
                        WholeIndex = WholeIndex + NextIndex
                    End If
            Else
                If WholeIndex > 1 Then
                    .Range("F" & i).Value = WholeIndex

                End If

                WholeIndex = 0

            End If

        Next i

    End With

End Sub