首页 文章

宏来查找重复行

提问于
浏览
0

我正在寻找一个宏来查找电子表格中的重复行 . 到目前为止,我已经提出了这组代码:

Application.ScreenUpdating = False

For Each cell In ActiveSheet.UsedRange.Columns("A").Cells
    For Each cell2 In ActiveSheet.UsedRange.Columns("A").Cells 'Loop through entire column A for each iteration in nested for loop
        If Cells(y, 1).Value = Cells(z, 1).Value Then 'Duplicate value found
            For icol = 1 To 19
                If Cells(y, icol).Value = Cells(z, icol).Value Then 'If cell value in current row matches, highlight red
                    Cells(z, icol).Interior.ColorIndex = 3
                End If
            Next icol
        End If

        z = z + 1
    Next cell2
    y = y + 1 'Next cell
    z = y + 1 'Next cell (y+1)
Next cell
Application.ScreenUpdating = True

我已经用嵌套的foor循环来解决这个问题 . 宏应该在A列中查找重复值 . 如果找到宏,则循环遍历该行以检查整行是否匹配 . 然后,该行中的每个匹配单元格都以红色突出显示当行数不是太大时,这似乎在小规模下工作正常 . 但是,当将此宏应用于具有7000行的电子表格时,Excel会冻结并崩溃 . 我怀疑这与嵌套的foor循环有关 . 对此有更快更实用的方法吗?

1 回答

  • 0

    尝试条件格式化而不是硬编码红色单元格填充 .

    Option Explicit
    
    Sub dupeRed()
        Dim lr As Long, lc As Long
    
        With Worksheets("sheet1")
            lr = .Cells(.Rows.Count, "A").End(xlUp).Row
            lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
            With .Range(.Cells(2, "A"), .Cells(lr, lc))
                .FormatConditions.Delete
                .FormatConditions.Add Type:=xlExpression, _
                  Formula1:="=AND(COUNTIF($A$1:$A1, $A2), A2=INDEX(A:A, MATCH($A2, $A:$A, 0)))"
                .FormatConditions(.FormatConditions.Count).Interior.Color = vbRed
            End With
        End With
    End Sub
    

相关问题