VBA中的求和范围环 [英] Sum range-loop in VBA

查看:56
本文介绍了VBA中的求和范围环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对从I列到T列的行求和,并将结果显示在V列.

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

当前,我的代码是:

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

我收到错误消息:运行时错误'1004':对象'Global'的方法'Range'失败"

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

我在做什么错了?

推荐答案

带有Nathan_Sav的更正的初始宏使代码正常工作.但是,使用了另一种方法来优化运行时间.在这里:

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

这篇关于VBA中的求和范围环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆