比较2行并突出显示差异

时间:2017-07-27 05:27:08

标签: excel vba compare

需要一些帮助来比较Excel中的两行并突出显示差异。

我有这段代码:

With ActiveSheet

    Last_Column = .Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column

    For lLoop = 1 To Last_Column
        If .Cells(1, lLoop).VALUE <> .Cells(2, lLoop).VALUE Then 
           .Cells(1, lLoop).Interior.ColorIndex = 4             
        End If    
    Next

End With

但它仅比较前两行。你能帮我比较一下行(1&amp; 2,3&amp; 4,5&amp; 6等)直到表格结尾并突出显示差异。

2 个答案:

答案 0 :(得分:1)

尝试下面的代码,代码注释中的解释:

Option Explicit

Sub CompareRows()

Dim i As Long, Col As Long
Dim LastRow As Long, Last_Column As Long

With Worksheets("Sheet1") '<-- modify to your sheet's name (don't rely on ActiveSheet)
    ' get last row
    LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    ' first add a loop of rows, step every 2
    For i = 1 To LastRow Step 2
        Last_Column = .Cells(i, .Columns.Count).End(xlToLeft).Column  ' get last column in current row

        ' loop through columns
        For Col = 1 To Last_Column
            If .Cells(i, Col).Value <> .Cells(i + 1, Col).Value Then
                .Cells(i, Col).Interior.ColorIndex = 4
            End If
        Next Col            
    Next i
End With

End Sub

答案 1 :(得分:0)

您拥有的代码仅适用于第1行和第2行,因为您在代码中对它们进行了硬编码,并且您循环遍历不循环遍历行的列。

你需要两个循环,一个循环遍历行,另一个循环遍历列。

试一试......

Sub CompareRows()
Dim LastRow As Long, LastColumn As Long
Dim i As Long, j As Long
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For i = 1 To LastRow Step 2
    For j = 1 To LastColumn
        If Cells(i, j) <> Cells(i + 1, j) Then Cells(i, j).Interior.ColorIndex = 4
    Next j
Next i
End Sub