Excel / VBA - 循环范围

时间:2015-05-21 15:37:47

标签: excel loops excel-vba range vba

我有以下代码:

TotalCount = Application.Sum(Worksheets("Data").Range("B14:G14"))
Sheets("Data").Range("H14") = TotalCount
TotalCount = Application.Sum(Worksheets("Data").Range("B13:G13"))
Sheets("Data").Range("H13") = TotalCount
TotalCount = Application.Sum(Worksheets("Data").Range("B12:G12"))
Sheets("Data").Range("H12") = TotalCount
TotalCount = Application.Sum(Worksheets("Data").Range("B11:G11"))
Sheets("Data").Range("H11") = TotalCount

正如你所看到的......它效率不高。问题是,我找不到一个循环解决方案,使其更好。当我尝试创建一个循环时,我得到的结果我不期望或它不起作用。我正处于需要帮助的地步......帮忙!并提前感谢你。

6 个答案:

答案 0 :(得分:1)

这可以用H单元格中的公式替换。

或VBA:

Dim i As Long
Dim rngA As Range: Set rngA = Worksheets("Data").Range("B14:G14")
Dim rngB As Range: Set rngB = Worksheets("Data").Range("H14")

For i = 0 To 3
    rngB.Offset(-i, 0).Value = Application.Sum(rngA.Offset(-i, 0))
Next

你也可以:

With Sheets("Data")
    .Range("H14") = Application.Sum(.Range("B14:G14"))
    ....
End With

答案 1 :(得分:1)

或者,只是为了好玩:

Dim i as integer
for i = 14 to 11 step -1
  Sheets("Data").Range("H" & i).Formula = "=SUM(B" & i & ":G" & i)
next

答案 2 :(得分:0)

For i = 1 to 4
    For t = 1 to 6
        TotalCount = Worksheets("Data").Cells(i+10,t+1).Value + TotalCount
    Next t
    Worksheets("Data").Cells(i+10,11).Value = TotalCount
    TotalCount = 0 'reset TotalCount
Next i

只要你不介意宏向相反的方向发展,那就应该达到你想要的目的。

答案 3 :(得分:0)

我们可以使用循环

Sub UseLoop()
   With Sheets("Data")
   For i = 11 To 14
      TotalCount = Application.Sum(.Range("B" & i & ":G" & i))
      .Range("H" & i) = TotalCount
   Next i
   End With
End Sub

答案 4 :(得分:0)

你不需要循环,只需要一点魔力:)

Worksheets("Data").Range("H11:H14").Formula = "=B:B+C:C+D:D+E:E+F:F+G:G"

如果您不喜欢公式添加

Range("H11:H14").Value2 = Range("H11:H14").Value2

答案 5 :(得分:0)

Range("H11:H14").Formula = "=SUM(B11:G11)"