如何获取最接近日期的记录?

时间:2016-07-26 02:05:22

标签: excel vba excel-vba

这是excel原始数据示例

  • StaffID日期累计余额
  • s15 15/12/2015 31
  • s15 31/12/2015 64
  • s15 3/4/2016 65
  • S98 13/4/2016 65
  • ......

现在我想在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

1 个答案:

答案 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之后按字母顺序对表进行排序。

它是如何运作的

  1. 它循环遍历行,检查当前行到startdate的距离。
  2. 如果距离更接近开始日期,则该行的行保存在closestDistLine
  3. 如果找到当前staff-id的所有条目,则最近距离行中的staff-id和值将写入56
  4. 列中

    HTH

相关问题