将循环值添加到下一个循环

时间:2015-03-24 10:14:08

标签: vba loops sum

是否可以保留循环的值并将其添加到循环的下一轮?我试图找到两列日期之间的差异,并将差异加在一起(以查找以后的平均天数)。 到目前为止我的代码是:

Sub macro1()
Dim d1
Dim d2
Dim i As Integer
Set wf = Application.WorksheetFunction

For i = 1 To 10
d1 = Cells(i, 1)
d2 = Cells(i, 2)
sdays = wf.NetworkDays(d1, d2)
Range("D4") = (the sum of the loops)

Next i

End Sub

1 个答案:

答案 0 :(得分:0)

试试这个 变量SumOfDates会在循环时跟踪日期总和,然后将该值粘贴到您的范围D4

Sub macro1()
Dim d1
Dim d2
Dim i As Integer
Dim SumOfDates 
Set wf = Application.WorksheetFunction

SumOfDates =0

For i = 1 To 10
d1 = Cells(i, 1)
d2 = Cells(i, 2)
sdays = wf.NetworkDays(d1, d2)

SumOfDates = SumOfDates + sdays

Next i

Range("D4").Value = SumOfDates

End Sub