Excel:对具有相同值的相邻行求和

时间:2015-01-07 11:20:26

标签: excel excel-vba vba

我有一个具有以下结构的表:

Timestamp    Name    Value
01/01/2013   X       20
01/01/2013   Y        5
01/01/2013   Y        3
01/01/2013   X        7
01/02/2013   X       15
01/02/2013   X        1  
01/02/2013   Z        8
01/03/2013   Y        1

我想将相同行的Value与相同的Name相加到第一行(在行上保持相同的Timestamp和其他值,只有{{1} }已更新)。可以有任意数量的连续出现,为了示例,我只放了两个。上面示例的结果应如下所示:

Value

1 个答案:

答案 0 :(得分:1)

Sub SumAdjacent()
Dim TimeStamp As Date
Dim Name As String
Dim Value As Integer
k = 1
For i = 2 To 80 'range of your data from secound row to 80row(or whatewer you want)
    Value = 0
    TimeStamp = Sheets(1).Cells(i, 1).Value
    Name = Sheets(1).Cells(i, 2).Value
    Value = Sheets(1).Cells(i, 3).Value
    j = i + 1
    'check next row
CheckNextRow:
    If Sheets(1).Cells(j, 2) = Name Then
        Value = Value + Sheets(1).Cells(j, 3).Value
            j = j + 1
            GoTo CheckNextRow ' loop to check every next row value
    Else
        Sheets(2).Cells(k, 1).Value = TimeStamp
        Sheets(2).Cells(k, 2).Value = Name
        Sheets(2).Cells(k, 3).Value = Value
        k = k + 1
                i = j - 1
    End If
Next
End Sub