Sum range-loop in VBA

2019-09-02 12:19发布

I want to sum rows from column I to T and display the result in column V.

Currently, my code is:

Sub Sum_column_V()

Dim lastRow As Long, i As Integer, totalItoT As Double, sht As Worksheet

Set sht = ThisWorkbook.Worksheets("Summary")

lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

For i = 1 To lastRow
    totalItoT = WorksheetFunction.Sum(Range("I" & i & "T" & i))
Next
    sht.Range("V" & i) = totalItoT

End Sub

I get the error message: "Run-time error '1004': Method 'Range' of object' Global failed"

What am I doing wrong?

标签: vba for-loop sum
1条回答
▲ chillily
2楼-- · 2019-09-02 13:12

The initial macro with Nathan_Sav's correction made the code work. However, used a different approach to optimize running time. Here it is:

Sub Sum_column_V()
Sheets("Summary").Select

Dim j As Integer
j = 2

While Cells(j, 1) <> ""
Cells(j, 22) = Application.Sum(Range(Cells(j, 9), Cells(j, 20)))
j = j + 1
Wend


End Sub
查看更多
登录 后发表回答