Search code examples
excelvbaexcel-formulasum

How to sum cells and include previous sum?


I want to add two cell values.

Add column E and Column F values into Colum D:

[Add column E and Column F values into Colum D1

If I delete those values it should not affect the resultant cell.
If I change the value or if I add new values in those cells the values should add to the previous resultant cell.

E.g. Cell A1=6 and cell A2=4. Their sum in cell A3 will be 10.
If I change the values of both cells to A1=8 and A2=5 then A3 should be 23.


Solution

  • The simple code:

    Private Sub Worksheet_Change(ByVal Target As Range)
      If Target.Address <> [A1].Address And Target.Address <> [A2].Address Then Exit Sub
      If IsEmpty(Target) Or Not IsNumeric(Target) Then Exit Sub
      [A3] = [A3] + Target.Value
    End Sub
    

    This picture should help, I guess. enter image description here Use the latest code, please.

    If you need to sum 3 cells, e. g. A4 = A1 + A2 + A3:

    Private Sub Worksheet_Change(ByVal Target As Range)
      If Target.Address <> [A1].Address And Target.Address <> [A2].Address _ 
        And Target.Address <> [A3].Address Then Exit Sub
      If IsEmpty(Target) Or Not IsNumeric(Target) Then Exit Sub
      [A4] = [A4] + Target.Value
    End Sub
    

    If you need to have 2 triplets of cells, e. g. A3 = A1 + A2 and B3 = B1 + B2:

    Private Sub Worksheet_Change(ByVal Target As Range)
      If Target.Row > 2 Then Exit Sub
      If IsEmpty(Target) Or Not IsNumeric(Target) Then Exit Sub
      If Target.Column = 1 Then
        [A3] = [A3] + Target.Value
      ElseIf Target.Column = 2 Then
        [B3] = [B3] + Target.Value
      End If
    End Sub