I am creating a model in Excel in which a cell computes the sum of two cells and keeps adding to the value every time the two cells on which it is dependent change values. For example,
A + B = C
Instance 1: -> 5 + 5 = 10
Instance 2: -> 4 + 3 = 17
Instance 3: -> 2 + 3 = 22
and so on…
I believe this can be achieved through a VB script.
you only need to put the following code in the worksheet code pane:
Private Sub Worksheet_Change(ByVal Target As Range) If Intersect(Range("A1:A2"), Target) Is Nothing Then Exit Sub Range("B1") = Range("B1") + WorksheetFunction.sum(Range("A1:A2")) End Sub
of course you have to change:
all “A1:A2” occurrences to your actual cells to sum address
all “B1” occurrences to your actual cell holding the running sum address
Hold the running total in a Public variable (
total). Initialize this as the workbook opens, using the workbook_open event, to the sum of the two cells of interest. Then use a worksheet_change event to monitor changes to those two cells and, if either changes, add their new value to the existing value of
total. I have used cell
C1 to show the running total.
In a standard module:
Option Explicit Public total As Long Public targetCell As Range
In the ThisWorkbook code pane
Option Explicit Private Sub Workbook_Open() With ThisWorkbook.Worksheets("Sheet1") Set targetCell = .Range("C1") total = Application.WorksheetFunction.Sum(.Range("A1:B1")) targetCell = total End With End Sub
In the worksheet code pane where the cells to monitor are
Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) If Not Application.Intersect(Target, Range("A1")) Is Nothing Then total = total + Target targetCell = total End If If Not Application.Intersect(Target, Range("B1")) Is Nothing Then total = total + Target targetCell = total End If End Sub
Or correctly do what @DisplayName has done! I wrote this initially for a Debug.Print of total (not writing to cell) and forgot to re-factor.