Sum range-loop in VBA

[亡魂溺海] 提交于 2020-01-17 03:29:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34678282/sum-range-loop-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!