我只是VBA的初学者,所以如果有人能在这里帮助我真的很好:
我有一张年度销售数据的表格,如:
然而,可能是一件商品于2007年9月1日(2007年9月1日)开始销售,并于2010年4月1日(2010年4月1日)结束销售。
现在我想计算一个年度总体平均值。我这样做的方法是手工完成:
如果能给excel一个日期范围(09/01/2007到04/01/2010),它会让我的生活变得如此简单,它会给我输出:
0,665753(2007年为243/365)
1(2008年全年)
请参阅下面的图片,以便更容易理解:
答案 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