Calculate the sum of values in a column with VBA - Printable Version +- QP School (https://qomplainerzschool.lima-city.de) +-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3) +--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48) +--- Thread: Calculate the sum of values in a column with VBA (/showthread.php?tid=5247) |
Calculate the sum of values in a column with VBA - Qomplainerz - 07-27-2023 Example: Sub SumColumnValues() Dim lastRow As Long Dim sumResult As Double 'Find the last row with data in column A lastRow = Cells(Rows.Count, "A").End(xlUp).Row 'Calculate the sum of values in column A sumResult = Application.WorksheetFunction.Sum(Range("A1:A" & lastRow)) 'Display the sum in a message box MsgBox "The sum of values in column A is: " & sumResult End Sub Explanation: The code defines a subroutine named SumColumnValues. It declares two variables lastRow and sumResult, where lastRow is used to store the last row with data in column A, and sumResult stores the sum of values in column A. The Cells(Rows.Count, "A").End(xlUp).Row statement finds the last row with data in column A using the End method in combination with the xlUp direction. The Application.WorksheetFunction.Sum function is used to calculate the sum of the range Range("A1:A" & lastRow), which contains all the values in column A from row 1 to the last row. The calculated sum is then displayed in a message box using the MsgBox function. |