根据日期差计算实例数(Excel / VBA)

问题描述 投票:0回答:1

我有以下数据:

Excel Table Screen Capture

即:

收单人ID ||| 目标ID(无用)||| 日期

123 ||| 456 ||| 20/01/2020

789 ||| 910 ||| 28/02/2019

我想再增加一列,在此我可以为每个收购方统计过去三年来进行了多少次收购。因此,对于每个具有给定日期的收单方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表屏幕捕获,即:收单方ID |||目标ID(无用)|||日期123 ||| 456 ||| 20/01/2020 789 ||| 910 ||| 2019年2月28日,我需要额外的...

excel vba for-loop vlookup counting
1个回答
0
投票

对于A2:A10中的获取方和C2:C10中的日期,此公式在D2中进行,并计算满足以下所有条件的记录数:

© www.soinside.com 2019 - 2024. All rights reserved.