Search code examples
excelvbaautomationcalculated-columns

Automatically sum up Table column named payments to a cell from another sheet without a cmd button


Is there a way to automatically run a vba code that I have written for a sheet without manually running the code via a cmd button or the run code option in vba editor

Private Sub Worksheet_Change()

Dim sumrange As Range
Dim Sumcolumn As Double

Set sumrange = Sheets("Receipt Input").Range("TBL_receipts[Payments]")
Sumcolumn = Application.WorksheetFunction.Sum(sumrange)

Range("b3").Value = Sumcolumn

End Sub

This is the code I wrote

enter image description here

Above a screenshot of the error I get


Solution

  • This sub is in sheet where the table exists. Change the "targetWorkSheet" to the real target sheet name where save the sum

    Private Sub Worksheet_Change(ByVal Target As Range)
       Dim sumrange As Range
       Dim Sumcolumn As Double
       Set sumrange = Me.Range("TBL_receipts[Payments]")
       If Not Intersect(Target, sumrange) Is Nothing Then
          Sumcolumn = Application.WorksheetFunction.Sum(sumrange)
          'Application.EnableEvents = False
          Worksheets("targetWorkSheet").Range("B3").Value = Sumcolumn
          'Application.EnableEvents = True
       End If
    End Sub
    

    Copy the sum at Worksheets("targetWorkSheet").Range("B3") only if sumrange changes.