【问题标题】:Calculating averages over irregular time periods?计算不规则时间段的平均值?
【发布时间】:2018-01-26 16:57:25
【问题描述】:

我只是 VBA 的初学者,所以如果有人能在这里提供帮助,那就太好了:

我有一个包含年度销售数据的表格,例如:

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

但是,有可能某件商品在 2007 年的 9 月 1 日 (09/01/2007) 才开始销售,并在 2010 年的 2010 年 4 月 1 日 (04/01/2010) 结束销售。

现在我想计算一个整体的年度平均值。我的做法是全部手工完成:

  • 计算产品在 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,246575(2010 年的比率为 90/365)

请看下图以便于理解:

【问题讨论】:

  • 您没有向我们展示您的数据布局,您的电子表格上的开始销售数据和结束销售日期在哪里?如果您可以向我们展示图像或其他内容,那么制定答案会容易得多,而且如果您尝试过任何代码,您也应该展示它......
  • 谢谢!这是一个好点,我在这里上传了一张图片 (imgur.com/a/w7lWq) 让它更容易理解。到目前为止,我还没有使用过代码,主要是手工编写。

标签: excel vba


【解决方案1】:

为此,您只需要在单元格 G1 和 G2 上输入开始日期和结束日期,在列 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

【讨论】:

    猜你喜欢
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2019-06-22
    • 2020-03-02
    相关资源
    最近更新 更多