这是excel原始数据示例
现在我想在excel中生成一个报告。 本报告我必须显示每位员工从2016年1月1日至2016年3月3日开始累计余额。
启动累计余额是指2016年1月1日之前的累计余额。
例如,对于员工S15,余额应为64(2016年1月1日之前最接近的累计余额。
在这种情况下有用的任何VBA函数或方法来获取最接近的日期记录,以便我可以获取该记录字段(Balance)。
顺便说一句,开始日期(1/1/2016)应存储在日期类型变量 -
中startdate
我的意思是有任何vba功能
说,abc(2016年1月1日,表1(范围(A:A)) 它可以帮助我找到最接近2016年1月1日和2016年1月1日之前该列范围内的日期(A:A)
输出:2015年12月31日
然后,我可以进行下一步:在该行中获得余额-31/12/2015
答案 0 :(得分:0)
我会提供这个答案,但我必须强调,评论中提出的批评仍然是合理的。
Sub findClosestDate()
Dim ws As Worksheet
Dim i, j, currDist As Long
Dim startDate As Date
Set ws = Worksheets(1)
With ws
i = 1
j = 1
closestDistLine = 1
startDate = "01.01.2016"
currDist = .Cells(i, 2) - startDate
Do While .Cells(i, 1) <> ""
newDist = .Cells(i, 2) - startDate
If newDist >= currDist Then
closestDistLine = i
currDist = newDist
End If
If .Cells(i, 1) <> .Cells(i + 1, 1) Then
.Cells(j, 5) = .Cells(i, 1)
.Cells(j, 6) = .Cells(closestDistLine, 3)
currDist = .Cells(i + 1, 2) - startDate
newDist = .Cells(i + 1, 2) - startDate
j = j + 1
End If
i = i + 1
Loop
End With
End Sub
要使此代码生效,您必须在staff-id之后按字母顺序对表进行排序。
它是如何运作的
closestDistLine
5
和6
HTH