【问题标题】:Highlight Duplicates in a single Range突出显示单个范围内的重复项
【发布时间】:2016-07-14 20:57:56
【问题描述】:

假设 Range 是连续的并且是单列。

我想突出显示上述范围的重复条目。我的 VBA 如下,但未按预期运行。主题是使用 OFFSET 将第一个单元格值与其底部值进行比较

Sub CompareSingleRange()
Dim rangeToUse1 As Range, rangeToUse2 As Range, cell1 As Range, cell2 As Range
' Assume Selection is contiguous
Set rangeToUse1 = Selection
Set rangeToUse2 = Selection
    For Each cell1 In rangeToUse1
        For Each cell2 In rangeToUse2
           If cell1.Value = cell2.Offset(1,0).Value Then
            cell1.Interior.ColorIndex = 38
            End If
        Next cell2
    Next cell1
End Sub

【问题讨论】:

    标签: vba excel duplicates conditional-formatting


    【解决方案1】:

    尝试条件格式规则。如果看起来更简单,请编写代码。

    With Worksheets("Sheet1")
        With .Range(.Cells(2, 1), .Cells(Rows.Count, 1).End(xlUp))
            .FormatConditions.Delete
            .FormatConditions.AddUniqueValues
            With .FormatConditions(1)
                .Interior.Color = vbGreen
            End With
        End With
    End With
    

               

    【讨论】:

      【解决方案2】:

      您可以使用 Excel Worksheet Functions 来完成此任务;否则,“纯”VBA 解决方案如下所示(您只需稍微修改您原来的 Sub 附加条件):

      Sub FindDuplicates()
          Dim rangeToUse1 As Range, cell1 As Range, cell2 As Range
          Set rangeToUse1 = Selection
          For Each cell1 In rangeToUse1
              For Each cell2 In rangeToUse1
                 If cell1.Value = cell2.Value And cell1.Row <> cell2.Row Then
                    cell1.Interior.ColorIndex = 38
                 End If
              Next cell2
          Next cell1
      End Sub
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        你只需要一个单循环

        Sub CompareSingleRange()
            Dim rangeToUse1 As Range, cell1 As Range
            Dim wf As WorksheetFunction
            Set wf = Application.WorksheetFunction
            ' Assume Selection is contiguous
            Set rangeToUse1 = Selection
        
                For Each cell1 In rangeToUse1
                        If wf.CountIf(rangeToUse1, cell1) > 1 Then
                            cell1.Interior.ColorIndex = 38
                        End If
                Next cell1
        End Sub
        

        【讨论】:

        • 优秀。这甚至避免了以前解决方案RANGE维度的限制
        猜你喜欢
        • 1970-01-01
        • 2020-05-19
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 2020-03-26
        • 1970-01-01
        • 2015-11-10
        相关资源
        最近更新 更多