07-27-2023, 08:18 AM
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.
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.