扫描并比较两行

时间:2017-03-07 16:15:11

标签: excel vba excel-vba

目前有一个Excel文档,其中一个模块连接到一个按钮。

Excel文档类似于以下内容:

ROW  |  COLUMN C   |  COLUMN K
1       808           253
2       808           256
3       908           355
4       908           355
5       908           356
6       907           253
7       907           253

当我点击按钮时,以下模块启动:

Sub scan()
    Dim dataRange As Range
    Dim dataRange2 As Range
    Dim oneCell As Range
    Dim oneCell2 As Range

    With ThisWorkbook.Sheets("Resource Info").Range("C:C")
        Set dataRange = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    With ThisWorkbook.Sheets("Resource Info").Range("K:K")
        Set dataRange2 = Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    For Each oneCell In dataRange
        If Application.WorksheetFunction.CountIf(dataRange, oneCell) > 1 Then
            For Each oneCell2 In dataRange2
                If Application.WorksheetFunction.CountIf(dataRange, oneCell) > 1 And Application.WorksheetFunction.CountIf(dataRange2, oneCell2) <> 1 Then
                    With oneCell
                        .EntireRow.Interior.ColorIndex = 6
                    End With
                End If
            Next oneCell2
        End If
    Next oneCell
End Sub

我试图只有第1,2,3,4,5行才会突出显示,因为列C匹配但列K数据与列C分组不匹配。

当前模块I突出显示所有行,无论列K中包含什么。

1 个答案:

答案 0 :(得分:2)

将您的多个Application.CountIf函数替换为一个Appl;ication.CountIfs

Sub scan()
    Dim rw As Long

    With ThisWorkbook.Sheets("Resource Info")
        .UsedRange.offset(1, 0).EntireRow.Interior.Pattern = xlNone
        For rw = 2 To .Cells(.Rows.Count, "C").End(xlUp).Row
            If CBool(Application.CountIfs(.Columns("C"), .Cells(rw, "C").Value2, .Columns("K"), "<>" & .Cells(rw, "K"))) Then
                .Rows(rw).EntireRow.Interior.ColorIndex = 6
            End If
        Next rw
    End With

End Sub

enter image description here