【问题标题】:Excel VBA Duplicates in one columns unique in anotherExcel VBA在一个列中重复在另一列中是唯一的
【发布时间】:2015-07-04 09:48:55
【问题描述】:

这几天我一直在尝试解决这个问题,但未能提出或找到类似的解决方案。我试图在单个列中突出显示重复项,而它们在另一个列中是不同的值。

例如,有时在 G 列中存在重复名称,但仅当值列 D 唯一时才需要标记(突出显示)它们。因此,使用下面的示例,最终结果应该只会突出显示 Elizabeth Moore。

Column D    Column G
116023339   Alan Fluder
116023339   Alan Fluder
116023347   Elizabeth Moore
116025757   Elizabeth Moore
116025048   A. Lavoie

如果有帮助,下面是我用作起点的代码。

Sub test()

Dim cel As Variant
Dim myCell As Variant
Dim myrng As Range
Dim myRange As Range
Dim CellValue As Long

Set myrng = Range("G2:G" & Range("G" & Rows.Count).End(xlUp).Row)
Set myRange = Range("D2:D" & Range("D" & Rows.Count).End(xlUp).Row)

For Each cel In myrng
    If Application.WorksheetFunction.CountIf(myrng, cel) > 1 Then
        For Each myCell In myRange
            If Application.WorksheetFunction.CountIf(myRange, myCell) = 1        Then
                myCell.Offset(0, 3).Interior.ColorIndex = 6
            End If
        Next myCell
    End If
Next cel

End Sub

我应该补充一点,我现在的解决方案是分离循环,其中一个突出显示所有列 G 重复,然后第二个循环取消突出​​显示 D 列被重复。

【问题讨论】:

  • 你可以用一个公式来做到这一点:=COUNTIFS(D:D,D2,G:G,G2)<>COUNTIF(G:G,G2) 对符合你描述的情况来说是 TRUE。

标签: vba excel


【解决方案1】:

如果您可以使用公式,@Tim 的建议效果很好。修复 VBA:


Option Explicit

Sub test()

    Const ROW_OFFSET As Byte = 2

    Dim cel As Range
    Dim rng1 As Range
    Dim rng2 As Range
    Dim cRow As Long
    Dim lRow As Long

    Set rng1 = Range("G" & ROW_OFFSET & ":G" & Range("G" & Rows.Count).End(xlUp).Row)
    Set rng2 = Range("D" & ROW_OFFSET & ":D" & Range("D" & Rows.Count).End(xlUp).Row)

    With Application.WorksheetFunction
        For Each cel In rng1
            If .CountIf(rng1, cel) > 1 Then
                If .CountIf(rng2, rng2.Cells(cel.Row - (ROW_OFFSET - 1), 1)) = 1 Then
                    cel.Interior.ColorIndex = 6
                End If
            End If
        Next cel
    End With
End Sub

如果列是同步的,则不需要内部 For

我使用了 ROW_OFFSET 常量来强调列之间的对齐

.

【讨论】:

    猜你喜欢
    • 2021-10-17
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    相关资源
    最近更新 更多