Comparing Columns and Highlight the Matching Data

2019-07-21 20:35发布

I Need to compare Column B in Sheet 2 with Column C in Sheet 3 and highlight the cells with matching data in Column B (Sheet 2).

Have used the following formula in Conditional Formatting

which works =NOT(ISNA(VLOOKUP(Sheet3!C,Sheet2!B,1,FALSE))) with Format type being a

particular color say Yellow Interior.colorindex = 6

How to implement the same using code in VBA?

2条回答
Explosion°爆炸
2楼-- · 2019-07-21 20:51

you can do it like this

Sub CompareAndHighlight()

    Dim rng1 As Range, rng2 As Range, i As Long, j As Long
    For i = 1 To Sheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
        Set rng1 = Sheets("Sheet2").Range("B" & i)
        For j = 1 To Sheets("Sheet3").Range("C" & Rows.Count).End(xlUp).Row
            Set rng2 = Sheets("Sheet3").Range("C" & j)
            If StrComp(Trim(rng1.Text), Trim(rng2.Text), vbTextCompare) = 0 Then
                rng1.Interior.Color = RGB(255, 255, 0)
            End If
            Set rng2 = Nothing
        Next j
        Set rng1 = Nothing
    Next i

End Sub

the code checks all cells in Sheet2 column B against each cell from Sheet3 column C and if they match it highlights cells on Sheet2 in Column B in yellow

查看更多
我命由我不由天
3楼-- · 2019-07-21 20:55

I would do it this way:

Dim c As Range

For Each c In Range("sheet2!b:b")
    If c.Value <> "" And Sheets("Sheet3").Cells(c.Row, 3).Value = c.Value Then
        c.Interior.Color = vbYellow
    End If
Next
查看更多
登录 后发表回答