Home » excel » Excel VBA – increase accuracy of Match function

Excel VBA – increase accuracy of Match function

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am using a Match function in my program, its main purpose is to compare an input typed by the user and then loop into a database and do something every time there is a match.

Currently, I am working with this :

Function Match(searchStr As Variant, matchStr As Variant) As Boolean
Match = False
If (IsNull(searchStr) Or IsNull(matchStr)) Then Exit Function
If (matchStr = "") Or (searchStr = "") Then Exit Function

Dim f As Variant
f = InStr(1, CStr(searchStr), CStr(matchStr), vbTextCompare)
If IsNull(f) Then Exit Function
Match = f > 0

End Function

And then when it is used :

If Match(sCurrent.Range("A" & i).Value, cell.Value) Then

Here is my problem :

This is way too inaccurate. If I have in my database “Foxtrot Hotel”, this function will find a match whenever the user types “F” “Fo” “Fox” “ox” “xtro” “t hot” and so on, so whenever there is a string of character included in the complete sentence.

What I want is to make my Match function identify only complete words. So in this case, to reveal a match only for three specific cases : “Foxtrot” “Hotel” and “Foxtrot Hotel”.

I have read about an attribute called “lookat” which can do this kind of stuff with the Find function (lookat:=xlwhole), do you know if something similar can be inserted in my Match function?

Thanks !

How to&Answers:

You could use a like so. This one runs a case-insensitive match on whole words only (using word boundaries around the word being searched).

  • False (fo is followed by a letter, not a word boundary)
  • True
  • True
  • False (FOXTROT h not followed by a word boundary)

Find wont work with xlWhole for you – that will look to match the entire cell contents, not a single word within the contents.

Function WordMatch(searchStr As Variant, matchStr As Variant) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\b" & matchStr & "\b"
.ignorecase = True
WordMatch = .test(searchStr)
End With
Set objRegex = Nothing
End Function

Sub B()
Debug.Print WordMatch("foxtrot hotel", "fo")
Debug.Print WordMatch("foxtrot hotel", "hotel")
Debug.Print WordMatch("foxtrot hotel", "FOXTROT")
Debug.Print WordMatch("foxtrot hotel", "FOXTROT h")
End Sub