VBA根据两个条件对行之间的行进行计数

我想为每个数据集的每个id更改之间的距离(行数),如下所示:

change id distance 1 id 1 1 id 1 1 id 1 1 id 1 0 id 1 4 1 id 1 1 1 id 1 1 id 1 1 id 1 0 id 2 0 id 2 0 id 2 1 id 2 3 

现在我有一个代码,把距离作为行的总数,而不是在id级别。 有人可以帮我吗?

 Sub cnt() For i = 3 To Rows.Count If Cells(i, 1).Value <> Cells(i - 1, 1).Value And Cells(i, 2).Value = Cells(i - 1, 2).Value Then Cells(i, 3).Value = CStr(i - 2) End If Next i Exit Sub End Sub 

在你的代码中,你总是比较我到第二行。

 Cells(i, 3).Value = CStr(i - 2) 

每次改变或者id不同,这个“2”都需要改变。 我会做这样的事情(显式variables声明是因为我被Excel / VBA烧掉了,因为过去没有这样做)。

 Option Explicit Sub cnt() Dim currentSheet As Worksheet Dim targetRange As Range Set currentSheet = ActiveSheet Set targetRange = currentSheet.UsedRange Dim i As Long Dim x As Long x = 2 With targetRange For i = 3 To .Rows.Count If .Cells(i, 1).Value <> .Cells(i - 1, 1).Value And .Cells(i, 2).Value = .Cells(i - 1, 2).Value Then .Cells(i, 3).Value = CStr(i - x) x = i ElseIf .Cells(i, 2).Value <> .Cells(i - 1, 2).Value Then x = i End If Next i End With Exit Sub End Sub 

只是为了好玩,

这是一个你想要的公式。

把它放在C2中,然后复制/下拉:

 =IF(AND(A2<>A1,B2=B1),ROW(1:1)-MATCH(B2,B:B,0)+1-SUMIF($B$1:B1,B2,$C$1:C1),"") 

在这里输入图像说明