无论范围从何处开始,我都需要从“初始到最终”求和
Dim ws3 As Worksheet
Dim initial As Integer
Dim final As Integer
Dim period As Double
ws3 = Worksheets("Moving Averages")
initial = TextBox3.Value
final = TextBox4.Value
period = TextBox8.Value
For i = initial To final
ws3.Range("v1").Value = Application.Sum(ws3.Range("u" & i)) / period
Next i
答案 0 :(得分:0)
如果我正确地理解你,你想要对一系列单元格求和,这对于循环中的每次迭代递减一个单元格(顶行)。如果是这样,这应该可以解决问题。
这是我的设置,我在Sheet1的单元格A1-A10中有值1-10。
这是我正在使用的代码:
Public Sub SOExample()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim Final As Integer: Final = 10
Dim rng As Range
For i = 1 To Final
'Get a range which is the Initial cell to the Last
Set rng = ws.Range(ws.Cells(i, 1), ws.Cells(Final, 1))
'Sum from A1-A10, then A2-A10, A3-1A0 etc and add value in column B
ws.Cells(i, 2).Value2 = Application.WorksheetFunction.Sum(rng)
Next
End Sub
如果您愿意,您还应该能够使用公式获得相同的结果。对于你想要求和的每个单元格,请将此公式拉下来,在我看来这更容易。
=SUM(A1:$A$10)