问题
I have the following code:
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
As you can see... it's not very efficient. Problem is, i cant find a loop solution to make it better. When i try to create a loop i either get results i dont expect or it doesnt work. I'm at the point where i need some help... help! And thank you in advance.
回答1:
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
As long as you don't mind the macro going in the opposite direction, that should achieve what you're looking for.
回答2:
This could be replaced with formulas in the H
cells.
Or 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
You can also:
With Sheets("Data")
.Range("H14") = Application.Sum(.Range("B14:G14"))
....
End With
回答3:
or, just for fun:
Dim i as integer
for i = 14 to 11 step -1
Sheets("Data").Range("H" & i).Formula = "=SUM(B" & i & ":G" & i)
next
回答4:
We can use a Loop:
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
回答5:
You do not need a loop, just a bit of magic :)
Worksheets("Data").Range("H11:H14").Formula = "=B:B+C:C+D:D+E:E+F:F+G:G"
If you do not like the formula add
Range("H11:H14").Value2 = Range("H11:H14").Value2
回答6:
Range("H11:H14").Formula = "=SUM(B11:G11)"
来源:https://stackoverflow.com/questions/30378320/excel-vba-loop-through-range