使用excel vba按天将结果按周转换为结果

时间:2015-06-05 03:42:10

标签: excel vba excel-vba

在我的Excel表格中,我在A栏中有不同数量的日期,其中B列中的每个日期都有相关的总计。日期有点随机,但我想找到每周相关总数的总和。我是vba的新手,我在弄清楚如何计算每周的总数时遇到了一些麻烦。

我想的是psudo代码:

buttonClicked()
   Dim sum As Integer, tempDate As Date, current As Date, i As Integer, j As Integer, match As Boolean

   sum = 0
   tempDate = Range("A1").Value
   current = tempDate

   For i = 1 To Rows.Count 

       for j = 0 to 7
          tempDate = addDate(d, i, tempDate)           
          If cell(i,1).Value = tempDate Then sum = sum + cell(i, 2).Value
              match = true
              Break
           End If
        Next j

       If match = true Then tempDate = current
       Else
          `next open space in column D is current
          current = tempDate
          `next open space in column E is sum
          sum = 0
   Next i
end

请告诉我是否有更好的方法来解决此问题,而不是迭代整个列表并提前7天计算。我应该注意到A1已经被认为是星期天,而且我不确定应该如何实现注释掉的行。我会非常感谢任何建议。

2 个答案:

答案 0 :(得分:0)

如果您要从B列中查找一系列7行总和,那么使用本机工作表函数的此公式应该可以。

=SUM(INDEX(B:B, (ROW(1:1)-1)*7+1):INDEX(B:B, (ROW(1:1)-1)*7+7))

填写以连续一周的时间段。

Weekly subtotals

如果您可以提供开始日期(例如=MIN(A:A))并在连续的行中添加7,则每周开始日期可以是SUMIFS function的参考点。在E9中,

=SUMIFS(B:B,A:A, ">="&D9,A:A, "<"&D9+7)

根据需要填写。

如果需要VBA解决方案,则可以将该逻辑引入VBA子或函数。

答案 1 :(得分:0)

在其他列中,使用以下公式为每行指定相应的Year.WeekNumber

=CONCATENATE(YEAR(A1),".",TEXT(WEEKNUM(A1),"00"))

每个Year.Week的总计可以使用SUMIF公式或PivotTable获得。如果您使用PivotTable作为Dynamic Range

DataSource可以自动调整大小