VBA:根据重复标准分别对行值求和

时间:2017-04-16 11:50:23

标签: vba excel-vba excel

我想编写一个VBA代码,只要值为“1”就可以对行的值求和,然后只要值为“-1”就对行的值求和,然后将其循环直到该行为止空。

参见随附的屏幕截图

enter image description here

请注意,标准不会重复5次,而是经常更改。

2 个答案:

答案 0 :(得分:2)

如果您的数据从A2开始,请在C2使用此公式,然后在C列中复制/粘贴:

=IF(B2=B1,"",SUMPRODUCT(OFFSET(A2,,,MATCH(TRUE,B3:B$1000<>B2,0))))

答案 1 :(得分:0)

我编写了以下代码,这似乎有效。它希望您选择具有要求和的值的列(不是末尾的任何空格),并根据右侧的列将相关的总计添加到第三列。

Sub MyProc()

Dim inputRange As Range
Set inputRange = Selection

Dim Cell As Range
Dim RunningTotal As Integer
Dim VerticalOffset As Integer

Dim PreviousCellFlag As Integer
PreviousCellFlag = 0

For Each Cell In inputRange

    If Cell.Offset(0, 1) <> PreviousCellFlag Then

        PreviousCellFlag = Cell.Offset(0, 1)
        RunningTotal = 0
        VerticalOffset = 0

        While Cell.Offset(0, 1) = Cell.Offset(VerticalOffset, 1)
            RunningTotal = RunningTotal + Cell.Offset(VerticalOffset, 0).Value
            VerticalOffset = VerticalOffset + 1
        Wend

        Cell.Offset(0, 2) = RunningTotal
    Else
        Cell.Offset(0, 2) = ""
    End If

Next Cell

End Sub