比较两列并高亮显示特定文本

时间:2017-07-11 05:44:32

标签: excel vba excel-vba formatting conditional

我有两列A和B中的数据。然后我想比较A列中字符串值形式的数据和B列中的文本值(即单个WORD文本)。

例如:

                      Column A                               |  Column B
-------------------------------------------------------------|------------
School Assorted Shape Bead Collection, Assorted Size         |  Assorted
School Assorted Shape Bead Collection                        |  Bamboo
Yasutomo Bamboo Brush Holder, 6 in                           |  Holder
Yasutomo Calligraphy Brushes with Bamboo Vase, Set of 10     |  
                                                             |

在A栏中,'assorted'也是B栏中的文字,所以在这种情况下我想要突出显示文字。如果没有,那么不要突出显示。对于另一行,Bamboo在col中都重复。 A和col。乙

如果我将弹出一个消息框要求选择要比较的单元格区域,那就太棒了。

提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这个

Sub test()
    Dim arrKeyword As Variant, arrItem As Variant
    Dim dataRng As Range, keywordRng As Range, rng As Range, cel As Range

    Set dataRng = Application.InputBox(prompt:="Select Data Range", Title:="Range Select", Type:=8)
    Set keywordRng = Application.InputBox(prompt:="Select Keyword Range", Title:="Range Select", Type:=8)
    If Not dataRng Is Nothing And Not keywordRng Is Nothing Then
        For Each cel In dataRng
            For Each arrItem In keywordRng
                If InStr(cel.Value, arrItem) <> 0 Then
                    Debug.Print arrItem & " Exists"
                    cel.Interior.ColorIndex = 37 'change cel property as needed
                End If
            Next arrItem
        Next cel
    End If
End Sub

对于第一个输入框,在Column A中选择您的范围,在Column B中选择第二个输入框选择范围。见图片以供参考。

enter image description here

修改

Sub Test()
    Dim dataRng As Range, keywordRng As Range, rng As Range, cel As Range

    Set dataRng = Application.InputBox(prompt:="Select Data Range", Title:="Range Select", Type:=8)
    Set keywordRng = Application.InputBox(prompt:="Select Keyword Range", Title:="Range Select", Type:=8)
    If Not dataRng Is Nothing And Not keywordRng Is Nothing Then
        For Each cel In dataRng
            If InStr(cel.Value, cel.Offset(0, 1).Value) <> 0 Then
                    cel.Interior.ColorIndex = 37 'change cel property as needed
            End If
        Next cel
    End If
End Sub