【问题标题】:Find duplicate values within the same row (Excel)在同一行中查找重复值 (Excel)
【发布时间】:2016-11-11 23:08:36
【问题描述】:

我有一个地址列表,但某些记录的部分地址已重复。例如有些记录在 D 列和 E 列中都包含“London”。

我想查找并突出显示所有列中的任何重复值,但在同一行中。

到目前为止,我已经编写了下面的代码,但我希望它能够处理包含值的每一列,而不仅仅是我命名的两列。

Dim Lastrow As Long
Dim i As Long
Lastrow = Range("D" & Rows.Count).End(xlUp).Row
For i = 2 To Lastrow
    If Range("D" & i).Value = Range("E" & i).Value Then
        Range("E" & i).Interior.ColorIndex = 6
    End If
Next i

我试图寻找答案,但我只能找到突出显示整个重复行或不同列和行中的重复值的方法。

感谢您抽出宝贵时间阅读本文并为您提供任何帮助。

【问题讨论】:

  • 您可以使用条件格式来做到这一点,不需要 VBA。
  • @SJR 感谢 SJR,但除非我不正确地使用条件格式,否则它似乎也会突出显示具有匹配值的不同行。因此,例如,十行具有相同城镇的地址被突出显示,而不仅仅是每行中有重复的行。
  • 假设您的数据在 A1 到 B10 中。突出显示您的范围,使 A1 成为活动单元格(突出显示)。然后转到 CF,添加一个公式 = COUNTIF($A1:$A10,A1)>1 并选择您的格式。我认为这应该做你想做的。
  • 使用这个公式 = COUNTIF($A1:$B10,A1)>1 仍然会突出显示不同行上的值。因此,如果 A2 包含“Cat”而 B2 包含“Cat”,那么它们都会突出显示,但如果 A3 也是“Cat”,即使 B3 是“Dog”,它也会突出显示。 @SJR
  • 公式是=COUNTIF($A1:$A10,A1)>1,你改成B10是错误的。

标签: excel vba


【解决方案1】:

如果您真的想要一个 VBA 解决方案,这可以解决问题:

Sub JustCall()
Call DuplicatedInRangeByRow(Range("A1:D5"))
End Sub
Sub DuplicatedInRangeByRow(RangeToLook As Range)
Const ColorHighlight = vbYellow
Dim ItemRange As Range
Dim TotalRows As Long: TotalRows = IIf(RangeToLook.Row > 1, RangeToLook.Rows.Count + RangeToLook.Row - 1, RangeToLook.Rows.Count)
Dim TotalCols As Long: TotalCols = IIf(RangeToLook.Column > 1, RangeToLook.Columns.Count + RangeToLook.Column - 1, RangeToLook.Columns.Count)
Dim CounterCols As Long
Dim CounterRows As Long
Dim StartCol As Long
Dim SheetForRange As Worksheet: Set SheetForRange = RangeToLook.Parent
    For CounterRows = RangeToLook.Row To TotalRows
    For CounterCols = RangeToLook.Column To TotalCols
    StartCol = IIf(StartCol = 0, CounterCols, StartCol)
    With SheetForRange
    If CStr(.Cells(CounterRows, StartCol).Value) = CStr(.Cells(CounterRows, CounterCols).Value) And StartCol <> CounterCols Then .Cells(CounterRows, StartCol).Interior.Color = ColorHighlight: .Cells(CounterRows, CounterCols).Interior.Color = ColorHighlight
    End With
    Next CounterCols
    StartCol = 0
    Application.StatusBar = "Progress: " & CounterRows & " out of " & TotalRows & " Rows analyzed " & Format(CounterRows / TotalRows, "Percent")
    Next CounterRows
End Sub

【讨论】:

  • 很难理解 OP 想要什么。我将其视为行中的任何重复项,而不仅仅是第一列重复。按照我的理解,如果您将Cat 放在 D5 中,它将同时突出显示ParrotCat。但我可能错了。
  • @ScottCraner 无论是你的还是我的——至少应该解决它,哈哈。
  • 我希望有一个 VBA 解决方案,这完美地解决了我的问题!谢谢@Sgdva
【解决方案2】:

对于条件格式,您可以使用以下公式:

=COUNTIF($A1:$J1,A1)>1

其中$A1A1 指的是要应用格式的区域中最左上角的单元格。而$J1 是范围的右上角单元格。

密切注意什么是绝对的,什么是相对的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多