Excel 2016 - 删除单元格颜色为 X 或其他条件的重复项

Excel 2016 - Remove duplicates where cell color is X, or other condition

我有一个用户想要从包含 40 多千行的电子表格中删除重复的行。

看起来 Excel 的删除重复项功能只是保留了 value/row 的第一个实例,然后删除了后面的所有重复项。

他们想 select 根据(初始偏好)包含重复项的单元格的颜色保留哪些重复项。删除重复项是非常基本的,所以我无法做到这一点,即使我们可以提取单元格颜色(我认为我们可以使用下面的):

=CELL("color",E2)

并将颜色名称或其他一些值放在另一个单元格中,我认为这不能与删除重复项结合使用来实现他们想要的。

VB 是让我们实现这一目标的唯一途径吗?可能有人对实现这一目标的某些代码有任何建议吗?为了争论起见,假设他们有黄色和白色的细胞,并且想要去除白色。

以下代码将遍历 'Sheet1' 中的 'Column 1',将找到每个重复值并将其地址存储在数组中。然后它将迭代数组并检查每个地址单元格的颜色 - 如果它是黄色,它将删除重复项。

这完全符合您的要求(除了这里的黄色将被删除,因为它对我来说似乎更紧迫)。

例如这个数据:

以后VBA会变成这样 运行:

Sub sbFindDuplicatesInColumn_With_Color_Condition()

    Dim toDel(), i As Long
    Dim RNG As Range, Cell As Long

    'Declare and set the worksheet where your data is stored
    Dim sheet As Worksheet
    Set sheet = Worksheets("Sheet1")

    'Finding the last row in the Column 1
    lastRow = sheet.Cells(sheet.Rows.Count, 1).End(xlUp).Row

    'Set the range to the last row of data in the column
    Set RNG = Range("a1:a" & lastRow) 'set your range here

    'Iterate over the column, finding duplicates and store their address in an array
    For Cell = 1 To RNG.Cells.Count
        If Application.CountIf(RNG, RNG(Cell)) > 1 Then
            ReDim Preserve toDel(i)
            toDel(i) = RNG(Cell).Address
            i = i + 1
        End If
    Next
    'Iterate over the array and remove duplicates with specific color index (in this example - remove the yellow ones)
    For i = UBound(toDel) To LBound(toDel) Step -1
        If Range(toDel(i)).Cells.Interior.ColorIndex = 6 Then
            Range(toDel(i)).Cells.Value = ""
        End If
    Next i

End Sub

您可以根据 ColorIndex 属性 修改要删除其值的颜色(要删除白色,请将条件更改为 If Range(toDel(i)).Cells.Interior.ColorIndex = 2

这是 Excel ColorIndex colors 的一个很好的参考。