How to have a cell that displays the cumulative value of all values entered in another cell?
I want to have a cell on my spreadsheet that updates in a cumulative manner, in response to values being changed in another cell. What would the code for this cell be?
For example the original value of cell B2 is 3 and cell C2 shows the cumulative value of all numbers entered into cell B2. So initially C2 will show 3. Once the value of B2 is changed to 10, C2 displays 13 and so on.
Solution 1:
This will require VBA.
Something like this would work, it goes in the Sheet1
module through the VBA editor*. You can change the sheet name and ranges as needed. -
Sub worksheet_change(ByVal target As Range)
If Not Intersect(target, Range("B2")) Is Nothing Then
Range("C2") = Range("C2").Value + target.Value
End If
End Sub
However, this will error if the target is non-numeric. So you need to handle the errors like this -
Sub worksheet_change(ByVal target As Range)
If Not Intersect(target, Range("B2")) Is Nothing Then
If IsNumeric(target.Value) = False Then GoTo Error:
If IsNumeric(Range("C2").Value) = False Then GoTo Error:
Range("C2") = Range("C2").Value + target.Value
Exit Sub
Else: Exit Sub
End If
Error:
MsgBox ("Use a number!")
End Sub
*To get to the VBA editor, you must go to the office button, excel options and in the popular tag, place a checkmark in the box next to Show Developer tab in the Ribbon
. Then close that out, go to the developer tab and click the Visual Basic
button on the far left. The editor will open up and you will need to double click the Sheet1
(or whatever sheet this is on) module on the left pane.