VBA Search Multiple value to find match in Cell string

MHamid

Active Member
Joined
Jan 31, 2013
Messages
472
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
Hello,

Can anyone let me know if the below is possible? If so, how?

I am looking to create a vba code that will conduct multiple text searches within a cell and highlight the cell (any color) and change the found text to bold and red font. Would this be possible?
I have a list of keywords to search (B2:B90). I manually search for 89 keywords or key phrases against a paragraph that is found in one cell (AJ5). I would like to automate this process instead of manually searching every keyword/key phrase and then update the found word found keyword/key phrase in bold and red font.
Can this be done? If someone can point me to the right direction, that would be helpful .


Thank you,
 

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
Pointing you in the right direction (make the changes as suggested)

Code

VBA Code:
Option Explicit
Sub Highlight()
    Dim cellCheck As Range, myCount As Long, i As Long, arr
   
    Set cellCheck = Range("A1") '<< change range to "AJ5"
   
    arr = Range("B2:B5").Value  '<< change range to "B2:B90"
   
    For i = LBound(arr, 1) To UBound(arr, 1)
            For myCount = 1 To Len(cellCheck) - Len(arr(i, 1)) + 1
                If Mid(cellCheck, myCount, Len(arr(i, 1))) = arr(i, 1) Then
                    cellCheck.Characters(myCount, Len(arr(i, 1))).Font.Color = vbRed
                    cellCheck.Characters(myCount, Len(arr(i, 1))).Font.Bold = True
                End If
            Next myCount
    Next i
End Sub
 
Upvote 0
Another possible option with a lot less looping, but note ..
  • It is not clear whether your are looking for full words in AJ5 or just text strings. Note the two partial words highlighted in my sample below. Could be whole words if required - subject to possible punctuation issues.
  • This code is written for the possibility that less than all B2:B90 cells are filled but there must be no blanks cells within the list in column B.
  • Search is not case-sensitive (eg Blue/blue), but could be if needed
  • This will only work with your Windows platform, not MacOS
VBA Code:
Sub HighlightStrings()
  Dim RX As Object, M As Object
 
  Set RX = CreateObject("VBScript.RegExp")
  RX.Global = True
  RX.IgnoreCase = True
  With Range("AJ5")
    RX.Pattern = Join(Application.Transpose(Range("B2", Range("B91").End(xlUp)).Value), "|")
    If RX.test(.Value) Then .Interior.Color = vbYellow
    For Each M In RX.Execute(.Value)
      With .Characters(M.FirstIndex + 1, Len(M)).Font
        .Bold = True
        .Color = vbRed
      End With
    Next M
  End With
End Sub

My sample data and results:

1662368430825.png
 
Last edited:
Upvote 0
Hi Kevin and Peter,

I tested both your codes and they work very well. I know I said that the cell to be checked is AJ5, but I actually need the code to loop through all the cells in column AJ starting from cell AJ2 until the last cell with data in that column to run the same check. Does that make any sense?

Oh also, would it be possible to highlight some words in different color? The keywords/key phrases I have belong to different categories. The table below is my keyword/key phrases search. Column A is the category and column B is the keywords/key phrases to be searched. If color coding them into 7 different colors by category in Column A is not possible. Are there any other suggestions as to how I can tell which keyword/Key phrase found belongs to what category? I don't have any preference to the 7 color coding.

Categorykeywords
CoBCoB
CoBcontinuity
CoBresilienc
CoBBCP
CoBRTO
CoBCoB
CoBResilie
CoBRecovery
CoBDisaster
CoBContienge
CoBContinu
CoBCrisis
CoBBusiness Impact Analysis
CoBBIA
EUCEUC
EUCEnd User Computing
EUCSpreadsheet
EUCAccess DB
EUCAccess Database
Inter-AffiliateInter-Affiliate
Inter-AffiliateICSA
Inter-AffiliateIntra-Citi
Inter-Affiliateaffiliate
Inter-Affiliateservice agreement
information securityinformation security
information securityentitlement
information securityvulnerab
information securityPII
information securityprivileged access
information securityaccess to data
information securityencrypt
information securitypersonally identifiable information
information securityEERS
information securityEEMS
information securityFunctional IDs
PMProgram Management Office
PMPMO
PMProgram Management
PMProject Management
PMCITMS
PMCiti Project and Program Management Standard
PMCPPMS
PM(PM)
PMPMO governance
PM(CPMO)
PMCPMC
PMCompliance Project Management Office
PMCiti Program Management Council
TPMSRM
TPM3rd party
TPMadd on products
TPMadd-on products
TPMcasp
TPMco-branded
TPMcssmp
TPMesrm
TPMexit strategy
TPMexternal reconciliation
TPMfinancial evaluation
TPMmanaged service providers
TPMmaster service agreement
TPMnon-employee
TPMOut Sourc
TPMoutsou
TPMOut-Soure
TPMperformance monitoring
TPMperformance review
TPMPLSD
TPMProvider
TPMReg 23A
TPMReg 23B
TPMsensitive relationships
TPMService Level Agreement
TPMSLA
TPMstep project
TPMstep steering committee
TPMSub Contractor
TPMsubadvis
TPMsub-advis
TPMsubcontract
TPMsub-contract
TPMsupplier
TPMthird-party
TPMTPISA
TPMvendor
TPMTPM
TPMtp
TPMthird party
DMData Management


Thank you,
 
Last edited:
Upvote 0
Could you give us some representative sample data for column AJ to test with - say 10 rows that show the sort of variety that may occur in that column?
 
Upvote 0
Could you give us some representative sample data for column AJ to test with - say 10 rows that show the sort of variety that may occur in that column?
See if this with my made-up data does what you want. If there are problems then, as well as detailing those problems, please provide the requested sample data.

VBA Code:
Sub HighlightStringsByCategory()
  Dim d As Object, RX As Object, M As Object
  Dim a As Variant
  Dim c As Range
  Dim i As Long, Cat As Long
 
  Set d = CreateObject("Scripting.Dictionary")
  d.CompareMode = 1
  a = Range("A1", Range("B" & Rows.Count).End(xlUp)).Value
  Cat = 2
  For i = 2 To UBound(a)
    If a(i, 1) <> a(i - 1, 1) Then Cat = Cat + 1
    d(a(i, 2)) = Cat
  Next i
  Set RX = CreateObject("VBScript.RegExp")
  RX.Global = True
  RX.IgnoreCase = True
  RX.Pattern = Replace(Replace(Join(Application.Transpose(Range("B2", Range("B" & Rows.Count).End(xlUp)).Value), "|"), "(", "\("), ")", "\)")
  For Each c In Range("AJ2", Range("AJ" & Rows.Count).End(xlUp))
    With c
      If RX.Test(.Value) Then .Interior.Color = vbYellow
      For Each M In RX.Execute(.Value)
        With .Characters(M.FirstIndex + 1, Len(M)).Font
          .Bold = True
          .ColorIndex = d(CStr(M))
        End With
      Next M
    End With
  Next c
End Sub

I have your Category/Keyword list in A1:B90 and this is my result.

1662449072902.png


Due to the short length of some of keywords and the fact that we are matching anywhere in the text, you may find some false-positives showing up as in "topmost" in my AJ2 example above.
 
Upvote 0
Hello,

I don't have sample data because it can be almost anything since the user can write pretty much anything. It's ok if it finds false matches. This is just so the user can focus on the areas in a report where I am extracting data from where they can focus to make a determination.
Code works perfectly with the tweaks I made for the workbook I'll be using it in.
Quick question though, how does the coloring system work? Will it always be the same color for the category? As in, will EUC category always be red or will the first match found be colored red instead?
 
Upvote 0
Will it always be the same color for the category?
Yes each category will always be the same colour - see below.

However, I had made an error with the previous code in that I coloured the background yellow and also one of the categories gets coloured yellow - so any words in that category would be impossible to read. :oops:
In the new code below I have changed the background colour to grey if a keyword is found

The categories will always have these colours (assuming the categories retain the same order in your main keyword table)

MHamid.xlsm
A
1Category
2CoB
3EUC
4Inter-Affiliate
5information security
6PM
7TPM
8DM
Sheet3


The slightly changed code is ..

Rich (BB code):
Sub HighlightStringsByCategory_v2()
  Dim d As Object, RX As Object, M As Object
  Dim a As Variant
  Dim c As Range
  Dim i As Long, Cat As Long
  
  Set d = CreateObject("Scripting.Dictionary")
  d.CompareMode = 1
  a = Range("A1", Range("B" & Rows.Count).End(xlUp)).Value
  Cat = 2
  For i = 2 To UBound(a)
    If a(i, 1) <> a(i - 1, 1) Then Cat = Cat + 1
    d(a(i, 2)) = Cat
  Next i
  Set RX = CreateObject("VBScript.RegExp")
  RX.Global = True
  RX.IgnoreCase = True
  RX.Pattern = Replace(Replace(Join(Application.Transpose(Range("B2", Range("B" & Rows.Count).End(xlUp)).Value), "|"), "(", "\("), ")", "\)")
  For Each c In Range("AJ2", Range("AJ" & Rows.Count).End(xlUp))
    With c
      If RX.Test(.Value) Then .Interior.ColorIndex = 48
      For Each M In RX.Execute(.Value)
        With .Characters(M.FirstIndex + 1, Len(M)).Font
          .Bold = True
          .ColorIndex = d(CStr(M))
        End With
      Next M
    End With
  Next c
End Sub

And sample results re-done and cell AJ7 contains one keyword from each of the 7 categories.

1662518640080.png
 
Upvote 0
Solution

Forum statistics

Threads
1,223,904
Messages
6,175,295
Members
452,633
Latest member
DougMo

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