【发布时间】:2020-07-03 13:20:13
【问题描述】:
我有以下数据:
即:
收购方 ID ||| 目标 ID(无用)||| 日期
123 |||第456章 ||| 20/01/2020
789 ||| 910 ||| 28/02/2019
我想要一个额外的列,我可以在其中为每个收购者计算过去 3 年中进行了多少次收购。 因此,对于具有给定日期的每个收单方 ID,我需要计算该 ID 在距离该日期不到 3 年的日期出现的次数。
因此,如果收购方在 2020 年、2016 年、2015 年和 2014 年进行收购,则在每种情况下,该收购方的计数将分别为 0、2、1、0。
我尝试过使用 COUNTIFS()、IF ()、VLOOKUP(),但我无法得到想要的结果,因为一旦满足条件,它就会对所有 ID 求和,而与日期无关。
我也尝试在 VBA 上编写宏,但我的语言知识基本上是 0。我发布代码以防它更好地了解问题
Dim Sheet As Worksheet
Set dbs = ThisWorkbook.Sheets("db")
Dim i As Integer, j As Integer, count As Integer
lr = dbs.Cells(Rows.count, 1).End(xlUp).Row
x = 0
For i = 2 To lr
For j = i + 1 To lr
Set myrange = Range("i:lr")
If dbs.Cells(i, 4).Value - Application.WorksheetFunction.VLookup(dbs.Cells(i, 4).Value, myrange, 4, False) < 3 Then
'I get a bug with Application.WorksheetFunction.VLookup, it might be that an error must be dealt with in case of missing values
count = count + 1
End If
Next j
Next i
dbs.Cells(i, 5).Value = count
End Sub
非常感谢任何帮助,提前谢谢您。
【问题讨论】:
标签: excel vba for-loop vlookup counting