简体   繁体   中英

The sum of a column using macro Excel 2010 vba

I use this macro for calculating the sum but it doesn't work. This is what I tried so far:

Sub sum()

I = .Range("E2").End(xlDown).Row

cumul = 0
For E = 2 To I
 cumul = cumul + Cells(E, 2)
Next
Range("E7") = cumul

End Sub

If I understood you correctly, the code below will SUM all the values in Column E (starting from Cell E2), and will put the result in Cell B2. (you can modify the location easily)

Note : I've added "Option 2", instead of using a For loop, you can use the WorksheetFunction.Sum to sum all the values inside a Range without needing to iterate.

Code

Option Explicit

Sub SumColE()

Dim cumul As Long, I As Long, E As Long

With Worksheets("Sheet1") ' <-- modify "Sheet1" to your sheet's name
    I = .Range("E2").End(xlDown).Row '<-- get last row in Column E        
    cumul = 0

    ' option 1: using a loop
    For E = 2 To I
        cumul = cumul + .Range("E" & E) '<-- Sum up values in Column E
    Next E
    .Range("B2").Value = cumul '<-- put the result in B2

    ' option 2: using WorksheetFunction SUM
    .Range("B2").Value = Application.WorksheetFunction.Sum(.Range("E2:E" & I))        
End With

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM