0

It there a way to achieve something like this in Excel:

enter image description here

I am looking for way to highlight part of text in cell that differs from other cell. Difference can appear at any position in cell.

zwornik
  • 329
  • 7
  • 15

1 Answers1

1

Try this sub procedure.

Sub Macro5()
    Dim i As Long, j As Long, p As Long, arr1 As Variant, arr2 As Variant

    With Worksheets("sheet4")
        For i = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
            'remove previous character formatting
            .Cells(i, "A") = .Cells(i, "A").Value2
            .Cells(i, "B") = .Cells(i, "B").Value2

            'split cell values into arrays on a 'pipe' delimiter
            arr1 = Split(.Cells(i, "A").Value2, Chr(124))
            arr2 = Split(.Cells(i, "B").Value2, Chr(124))

            'found in column A; not found in column B
            For j = LBound(arr1) To UBound(arr1)
                If IsError(Application.Match(arr1(j), arr2, 0)) Then
                    p = InStr(1, .Cells(i, "A").Value2, arr1(j), vbTextCompare)
                    With .Cells(i, "A").Characters(Start:=p, Length:=Len(arr1(j))).Font
                        .Bold = True
                        .Color = vbRed
                    End With
                End If
            Next j

            'found in column B; not found in column A
            For j = LBound(arr2) To UBound(arr2)
                If IsError(Application.Match(arr2(j), arr1, 0)) Then
                    p = InStr(1, .Cells(i, "B").Value2, arr2(j), vbTextCompare)
                    With .Cells(i, "B").Characters(Start:=p, Length:=Len(arr2(j))).Font
                        .Bold = True
                        .Color = vbRed
                    End With
                End If
            Next j
        Next i
    End With
End Sub

enter image description here

  • It worked fine. I have placed it as new module and executed it. I've noticed that when I run macro for the first time it creates correct results but when I run it again on already highlighted cells, then it adds additional colors. Unfortunately I have very little knowledge about VBA/macros but this solution is encouraging to learn more. Many thanks for support! – zwornik Jun 11 '18 at 18:41
  • I forgot to mention that the oryginal input value for this task looked like that: "CAN|DEU|MEX|USA|VNM || CAN|DEU|GBR|MEX|USA" It was in one cell, and values to compare were separated by space-pipe-pipe-space. I have used formula in Excel to split one cell into two cells based on " || " separator. Can this macro be modified to work on oryginal values in one cell? – zwornik Jun 11 '18 at 18:50
  • 1
    I suppose you could dim another variant and use that to split on a double pipe. Then each element would be column A or B as the case may be. Getting p from the original isn't an issue since each would be missing from the other. –  Jun 11 '18 at 23:32