我的用户想要从包含40多万行的电子表格中删除重复的行。
看起来Excel删除重复项功能只是保留值/行的第一个实例,然后删除后面的所有重复项。
他们希望根据(初始偏好)选择要保留的副本,包含副本的单元格的颜色。删除重复是非常基本的,所以无法从我能看到的内容中做到这一点,即使我们可以提取单元格颜色(我想我们可以使用下面的内容):
=CELL("color",E2)
并将颜色名称或其他值放在另一个单元格中,我不认为这可以与删除重复项一起使用以达到他们想要的效果。
VB是否是唯一允许我们实现此目标的途径,并且可能有人对某些代码有任何建议吗?让我们说,为了论证,他们有黄色和白色的细胞,并且想要去除白色。
答案 0 :(得分:1)
以下代码将迭代'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的一个很好的参考。