1

I need to create an Excel document with updating totals in the A column, based on numbers entered in the B column. Each respective cell in row A should update based on its equivalent B cell value whenever a new value is added, and then the value entered into B is cleared once added to A.

I have gotten things working for one single row but don't have knowledge or understanding on how to best make this work for EACH cell pair in the entire column. I really don't want to copy and paste this 10,000 times and update the cells to reference the correct pair. Code for single cell:

Private bIgnoreEvent As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
    If bIgnoreEvent Then Exit Sub
    bIgnoreEvent = True
    Cells(1, 2) = Cells(1, 2) + Cells(1, 1)
    Cells(1, 1) = ""
    bIgnoreEvent = False
End Sub

I am hoping this can be achieved with a loop function, or a range of some sort.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
MBolt
  • 11
  • 1
  • What have you tried so far to get a loop working? [This](https://stackoverflow.com/questions/3875415/loop-through-each-cell-in-a-range-of-cells-when-given-a-range-object) may be useful – cybernetic.nomad Apr 29 '19 at 20:14

1 Answers1

0

This should work:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, c As Range

    'any updates in ColB?
    Set rng = Application.Intersect(Target, Me.Columns(2))

    If Not rng Is Nothing Then
        Application.EnableEvents = False '<< prevent re-triggering of event
        'Process each updated cell
        For Each c In rng
            If IsNumeric(c.Value) Then
                With c.Offset(0, -1)
                    .Value = .Value + c.Value
                End With
                c.ClearContents
            End If
        Next c
        Application.EnableEvents = True  '<< re-enable event
    End If

End Sub
Tim Williams
  • 154,628
  • 8
  • 97
  • 125