VBA needs to consider only exact math

Dannottheman

Board Regular
Joined
Dec 24, 2020
Messages
55
Office Version
  1. 2007
Hello,

I am currently using the VBA below which has been working great until now. The script is supposed to find and shading rows containing certain words but now it's shading incorrect rows. For example, it's supposed to shade a cell containing the word "test", but if the cell has the word "testicle", it should NOT shade the cell. Right now it's shading cells because some characters match the word (e.g. unit vs united). Can someone please modify the VBA below so that it only considers the whole word/exact match?


Option Explicit
Sub Dannottheman3()
Dim Cl As Range
Dim srch As Variant
For Each Cl In Range("A1", Range("A" & Rows.Count).End(xlUp))
For Each srch In Array("*quiz*", "*unit*", "*exam*", "*assessment*", "*test*") ' <= note the different use of the jolly (could be useful)
If LCase(Cl.Value) Like srch Then
Cl.Interior.Color = rgbLightBlue
Cl.Font.Bold = True
Exit For
End If
Next srch
Next Cl
End Sub
 

Some videos you may like

Excel Facts

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.

Rick Rothstein

MrExcel MVP
Joined
Apr 18, 2011
Messages
36,569
Office Version
  1. 2010
Platform
  1. Windows
Untested but I am pretty sure this will work. First, remove the asterisks from your Array function call...

For Each srch In Array("quiz", "unit", "exam", "assessment", "test")

Then replace your If..Then statement with this one...

If " " & LCase(Cl.Value) & " " Like "*[!a-z0-9]" & srch & "[!a-z0-9]*" Then

Those two changes should make your code work the way you indicated you want.
 
Solution

Dannottheman

Board Regular
Joined
Dec 24, 2020
Messages
55
Office Version
  1. 2007
Untested but I am pretty sure this will work. First, remove the asterisks from your Array function call...

For Each srch In Array("quiz", "unit", "exam", "assessment", "test")

Then replace your If..Then statement with this one...

If " " & LCase(Cl.Value) & " " Like "*[!a-z0-9]" & srch & "[!a-z0-9]*" Then

Those two changes should make your code work the way you indicated you want.
Yes, its working great. Thank you so much!
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
50,750
Office Version
  1. 365
Platform
  1. Windows
@Dannottheman
For future reference, you need to mark the post that helped you the most as the solution, not your own post saying it worked. I have changed it for you this time.
 

Watch MrExcel Video

Forum statistics

Threads
1,118,522
Messages
5,572,637
Members
412,476
Latest member
luihp329
Top