【发布时间】:2020-01-30 13:14:03
【问题描述】:
如果满足特定条件(E 列),我编写了以下代码来清除重复数据集。它扫描 1216 行数据(LastRow 有 1216 个命中)并清除重复项。我遇到的唯一问题是,如果我有两三个重复项,它只会删除一个重复项。
我编写了另一行代码,说明如果多次找到单个项目(B 列),则名为 statement 的变量等于 TRUE。所以我希望循环继续,直到数据集中没有重复项,这也会将变量变为 FALSE 并停止循环。然而,循环无限地继续。当我手动停止脚本时,它似乎已经清除了所有重复项。
Sub ClearDataSet()
Dim LastRow As Integer
Dim i As Integer
Dim Rng, cell As Range
Dim Statement As Boolean
Set ws1 = ThisWorkbook.Worksheets("sheet1")
Set Rng = ws1.Range(("D1"), ws1.Range("D1").End(xlDown))
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
ws1.Range("A1").CurrentRegion.Sort _
key1:=ws1.Range("D1"), order1:=xlAscending, _
Key2:=ws1.Range("E1"), order2:=xlAscending, Header:=xlYes
Do
For i = 2 To LastRow
If ws1.Cells(i, "D") = ws1.Cells(i + 1, "D") And _
(ws1.Cells(i, "E") < ws1.Cells(i + 1, "E") Or _
ws1.Cells(i, "E") = ws1.Cells(i + 1, "E")) Then
Rows(i).Delete
End If
Next i
For Each cell In Rng
If WorksheetFunction.CountIf(Rng, cell.Value) > 1 Then
Statement = True
End If
Next cell
Loop Until Statement <> True
End Sub
编辑:M Schalk 解决方案后调整(更高效)脚本
Sub ClearDataSet()
Dim LastRow As Integer
Dim i As Integer
Dim Rng, cell As Range
Dim Statement As Boolean
Dim StartTime As Long
Dim TimeElapsed As Long
StartTime = Timer
Set ws1 = ThisWorkbook.Worksheets("sheet1")
Set Rng = ws1.Range(("D1"), ws1.Range("D1").End(xlDown))
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
ws1.Range("A1").CurrentRegion.Sort _
key1:=ws1.Range("D1"), order1:=xlAscending, _
Key2:=ws1.Range("E1"), order2:=xlAscending, Header:=xlYes
For i = 2 To LastRow
If ws1.Cells(i, "D").Value = "" Then
GoTo OverStepcode
ElseIf _
ws1.Cells(i, "D") = ws1.Cells(i + 1, "D") And _
(ws1.Cells(i, "E") < ws1.Cells(i + 1, "E") Or _
ws1.Cells(i, "E") = ws1.Cells(i + 1, "E")) Then
Rows(i).Delete
i = i - 1
End If
Next i
OverStepcode:
TimeElapsed = Round(Timer - StartTime)
MsgBox "The code ran successfully in " & TimeElapsed & " seconds vbinformation"
End Sub
【问题讨论】:
-
我为我的解决方案添加了一个更轻量级且易于阅读的解决方案,您应该尝试一下。