找到重复项并删除整行使用Do While和If Loop

问题描述

我有需要删除重复项的大型数据集。数据有一个包含ID号的列-我想遍历该列以获取重复的ID。如果存在重复项,我希望代码删除重复项。

我正在使用的数据集总是具有相同的列-但行数发生变化,因为我将使用:

do while Cells(b,4).Value “”

然后在此循环中,我想要一个If循环来查找重复项并将其删除-如何最好地做到这一点?

解决方法

如Scott Craner所述,有一个基本的Excel功能可以处理此问题。

我的Excel工作表如下:

Col_D Col_E
    1     1
    1     1
    1     2
    1     2
    1     3
    2     1
    2     2
    2     2
    2     2
    2     3

从“数据”选项卡记录“删除重复项”,将产生以下VBA命令:

ActiveSheet.Range("$D$1:$E$11").RemoveDuplicates Columns:=Array(1,2),Header :=xlYes

含义如下:

Range("$D$1:$E$11")  : Remove the duplicates from that range
Columns:=Array(1,2) : Both column 1 (D) and 2 (E) need to be taken into account
                         (the duplicates of the combination of both columns)
Header :=xlYes       : A header row is present

结果是:

Col_A Col_B
    1     1
    1     2
    1     3
    2     1
    2     2
    2     3