计算不规则时间段的平均值?

时间:2018-01-25 09:45:49

标签: excel-vba vba excel

我只是VBA的初学者,所以如果有人能在这里帮助我真的很好:

我有一张年度销售数据的表格,如:

  • 2007年:15
  • 2008年:20
  • 2009年:25
  • 2010年:30

然而,可能是一件商品于2007年9月1日(2007年9月1日)开始销售,并于2010年4月1日(2010年4月1日)结束销售。

现在我想计算一个年度总体平均值。我这样做的方法是手工完成:

  • 计算2007年产品销售天数(09/01/2007 - 01/01/2007 = 243天)
  • 取比例(243/365 = 0,665753)并乘以2007年的销售额。2008年和2009年是全年,因此* 1. 2010年,我再次计算比率0,246576 [90 / 365天]。
  • 然后我将所有这些值加起来除以2,912329(0,665753 + 0,246575 + 1 + 1,因为2008/2009年都是全年)。

如果能给excel一个日期范围(09/01/2007到04/01/2010),它会让我的生活变得如此简单,它会给我输出:

  • 0,665753(2007年为243/365)

  • 1(2008年全年)

  • 1(2009年全年)
  • 0,246565(2010年比例为90/365)

请参阅下面的图片,以便更容易理解:

enter image description here

1 个答案:

答案 0 :(得分:0)

此操作所需的只是G1和G2单元格的开始日期和结束日期,以及A列和A列的每年销售额。 B,然后代码将填充您的因子并乘以列C& D,并在细胞A10上给你一个结果。因此,在您的示例中,您在第13行下方不需要任何内容​​。

Sub foo()

Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'get the last row with data on Column A

BeginningDate = Format(ws.Range("G1"), "dd/mm/yyyy") 'get the beginning date from cell G1
EndDate = Format(ws.Range("G2"), "dd/mm/yyyy") 'get the end date from cell G2

Years = DateDiff("yyyy", BeginningDate, EndDate) + 1 'get the number of years to run a loop

CurrentDate = BeginningDate

For i = 1 To Years 'loop as many years between dates
    LastDayOfYear = "31/12/" & Year(CurrentDate) 'get the last day of the given year
    DaysDiff = DateDiff("d", CurrentDate, EndDate) 'calculate the days between Current and EndDate
    If DaysDiff > 365 Then 'if more than a year between
        CurrentDays = DateDiff("d", CurrentDate, LastDayOfYear)
        If CurrentDays = 364 Then CurrentDays = 365 'uncomment this line if you want your calculations to assume every year has 365 days
        Factor = CurrentDays / 365
        ws.Cells(i + 1, 3) = Factor
        ws.Cells(i + 1, 4) = Factor * ws.Cells(i + 1, 2)
        CurrentDate = DateAdd("d", 1, LastDayOfYear)
    Else
        Factor = DaysDiff / 365
        ws.Cells(i + 1, 3) = Factor
        ws.Cells(i + 1, 4) = Factor * ws.Cells(i + 1, 2)
        CurrentDate = DateAdd("d", 1, LastDayOfYear)
    End If
Next i
ws.Range("A10").Value = WorksheetFunction.Sum(ws.Range("D2:D" & Years + 1)) / WorksheetFunction.Sum(ws.Range("C2:C" & Years + 1))
End Sub
相关问题