比较同一工作表中的行

时间:2018-09-20 10:10:19

标签: excel vba excel-vba

我是初学者。

我应该编写一个程序,将A,B,C,D,E列中所有行中的所有值与同一行中G,H,I,J和K列中的值进行比较。

如果它们都相等,那么我需要突出显示该行。 我编写了以下代码,但未执行:

Sub compare()

Dim C As Range
Dim D As Range
Dim lastRow As Integer
Dim rng As Range
Dim i As Integer
Dim j As Integer
Dim k As Integer

lastRow = ThisWorkbook.Worksheets("ComparingResult").UsedRange.Rows.Count
'lastColumn = ThisWorkbook.Worksheets("ComparingResult").UsedRange.Columns.Count

Set rng = Range("K:K")
rng.Value = Format(rng.Value, "dd.mm.yyyy")

For i = 2 To lastRow
    For j = 1 To 5
        For k = 7 To 11
            For Each C In ThisWorkbook.Worksheets("ComparingResult").Cells(i, j)
                For Each D In ThisWorkbook.Worksheets("ComparingResult").Cells(i, k)
                    If C = D Then
                        C.Interior.Color = RGB(102, 255, 255)
                        D.Interior.Color = RGB(102, 255, 255)
                    Else
                        C.Interior.Color = vbWhite
                        D.Interior.Color = vbWhite
                    End If
                Next k
            Next j
        Next i
    Next
Next
End Sub

有人可以帮我弄清楚这是怎么回事吗?

1 个答案:

答案 0 :(得分:0)

想想这就是你想要的。
它将匹配A2与G2:K2,B2与G2:K2 ...直至E2与G2:K2。 然后A3与G3:K3匹配,等等...

您可以使用条件格式来做到这一点。

Sub compare()

    Dim C As Range
    Dim D As Range
    Dim lastRow As Integer
    Dim rng As Range
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer

    lastRow = ThisWorkbook.Worksheets("ComparingResult").UsedRange.Rows.Count
    'lastColumn = ThisWorkbook.Worksheets("ComparingResult").UsedRange.Columns.Count

    Set rng = Range("K:K")

    rng.NumberFormat = "dd.mm.yyyy"

    For i = 2 To lastRow
        For j = 1 To 5
            For k = 7 To 11
                Set C = ThisWorkbook.Worksheets("ComparingResult").Cells(i, j)
                Debug.Print C.Address

                Set D = ThisWorkbook.Worksheets("ComparingResult").Cells(i, k)
                Debug.Print D.Address

                If C = D Then
                    C.Interior.Color = RGB(102, 255, 255)
                    D.Interior.Color = RGB(102, 255, 255)
                Else
                    C.Interior.Color = vbWhite
                    D.Interior.Color = vbWhite
                End If
            Next k
        Next j
    Next i

End Sub