我想计算数据集的每个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
答案 0 :(得分:1)
在您的代码中,您始终将i与第2行进行比较。
Cells(i, 3).Value = CStr(i - 2)
每次更改或ID不同时,“2”需要更改。我会做这样的事情(显式变量声明是因为我已经被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
答案 1 :(得分:0)