Vba 如何获取具有最近日期的记录?
下面是excel原始数据示例Vba 如何获取具有最近日期的记录?,vba,excel,Vba,Excel,下面是excel原始数据示例 记账日期累计余额 s15 2015年12月15日31 s15 2015年12月31日64 s15 2016年3月4日65 S98 13/4/2016 65 现在我想在excel中生成一个报告。 此报告我必须显示每个员工从2016年1月1日至2016年3月31日的累计余额 起始累计余额指2016年1月1日前的累计余额 例如,对于员工S15,余额应为64(最接近2016年1月1日之前的累计余额) 问题 在这种情况下,任何VBA函数或方法都可以用来获取最近的日期记录
- 记账日期累计余额
- s15 2015年12月15日31
- s15 2015年12月31日64
- s15 2016年3月4日65
- S98 13/4/2016 65
startdate
使现代化
我的意思是有vba功能吗
比如,abc(2016年1月1日,表1(范围(A:A))
它可以帮助我在该列中找到最接近2016年1月1日和2016年1月1日之前的日期-范围(A:A)
产出:2015年12月31日
然后,我可以做下一步:在那一行中取得平衡-2015年12月31日我将给出这个答案,但我必须强调,在评论中向您提出的批评仍然是合理的
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
子findClosestDate()
将ws设置为工作表
尺寸i、j、电流与长度相同
Dim startDate作为日期
设置ws=工作表(1)
与ws
i=1
j=1
closestDistLine=1
startDate=“01.01.2016”
currDist=.Cells(i,2)-起始日期
执行While.Cells(i,1)”
newDist=.Cells(i,2)-startDate
如果newDist>=currDist,则
closestDistLine=i
currDist=newDist
如果结束
如果.Cells(i,1).Cells(i+1,1)那么
.单元(j,5)=.单元(i,1)
.Cells(j,6)=.Cells(closestDistLine,3)
currDist=.Cells(i+1,2)-起始日期
newDist=.Cells(i+1,2)-startDate
j=j+1
如果结束
i=i+1
环
以
端接头
要使此代码起作用,您必须在staff-id之后按字母顺序对表进行排序
它是如何工作的
closestDistLine
5
和6
HTH您的问题太宽泛,或者根本不清楚。请参阅。为什么使用VBa?索引匹配的数组版本可以做到这一点。@Scott Craner在excel中实现代码并生成报告时,我使用VBa作为coding@ScottCraner我知道你的意思。但是我的数据类型是date,它不能执行这个功能如果有两个日期,会发生什么与2016年1月1日的距离相同,但值不同?如果我想再添加一个条件,则为wt。仅适用于范围内没有记录的员工(2016年1月1日-2016年3月31日),必须找到最接近的累计余额。例如,对于staff-S19,范围内有记录。无需为他检查最接近的累计余额。只需添加另一个
,如果-块包含Do While
-循环中当前的所有内容。首先尝试为自己想出一些东西。:)