Regex: match and highlight string

Nelson78

Well-known Member
Joined
Sep 11, 2017
Messages
526
Office Version
  1. 2007
Hello everybody.

I've to match a string - cellz - in a range of cells.

The task is ok like this:

VBA Code:
Dim cellz As Variant
    For Each cellz In sheet1.Range("A2:A" & lr_col)
                With CreateObject("VBScript.RegExp")
                    .Global = True
                    .IgnoreCase = True
                    .Pattern = "\b" & cellz & "\b"
                For Each r In sheet2.Range("AG2:AG" & lr_ris)
                    If .test(r.Value) Then r.Interior.Color = vbRed
                Next r
        End With
    Next cellz

As you can see, I'm able of highlighting the cells where the string is found:

Code:
 If .test(r.Value) Then r.Interior.Color = vbRed

But I need something more: I need to write in yellow characters the string when found.

I mean: imagine cellz = "Paris"

Imagine cell where I'm looking for = "I don't live in Paris but I live in London"

I need like this: "I don't live in Paris but I live in London"

How can I perform the task?
 
Last edited:
If you want search for the literal character '.' you'll need to escape it.

To do that you would need to replace '.' with '\.' in the pattern.

This point is ok.

The complication is: I have a long and dynamic "cellw list" (currently 17000 records, next time could be very different in quantity and strings).
I should say, before executing the match: if cellw contains ".", then substitute with "\.".

Could this operation be performed?
 
Upvote 0

Excel Facts

How to fill five years of quarters?
Type 1Q-2023 in a cell. Grab the fill handle and drag down or right. After 4Q-2023, Excel will jump to 1Q-2024. Dash can be any character.
You could try this.
Code:
.Pattern = "\b" & Replace(cellw.Value, ".","\.")  & "\b"
 
Upvote 0

Forum statistics

Threads
1,215,467
Messages
6,124,984
Members
449,201
Latest member
Lunzwe73

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top