Solved Find Whole Word in Text (1 Viewer)

MajP

You've got your good things, and you've got mine.
Local time
Yesterday, 19:08
Joined
May 21, 2018
Messages
8,529
This is in relation to the demo I am doing using VBA extensibility.

Does anyone have code to find a whole word in text? Want to pass in a line of text and search text and return if matched.

I am looking for strings of "code" in code so these are some of the possibilities.

If looking for "form1" it could be sorrounded by (),[],.,!,', or space

Forms!Form1.Controls
Forms("form1")
Forms_Form1
[Form1]
'Form1'

Also the thing I am searching might have these same characters within the string such as if looking for these strings
"Docmd.Openform"
"Forms!Form1"

Thanks. I assume this can be done with regex (not my strength) where whole word can be lead or followed with a non alpha numeric. But not sure how you do not return
Form123.
or Form1

My simple search got rid of all non alphnumeric characters and replaced with space. This worked fine for finding
Form1
but can no longer search for "Debug.print"
I can improve my search by only removing characers not in the search string (95%) solution.
 

ebs17

Well-known member
Local time
Today, 01:08
Joined
Feb 7, 2020
Messages
1,946
@Josef P. already gave you the hint to use regular expressions:
Code:
sPattern = "\bform1\b"
\b ... the comparison is on a boundary between word characters (\w) and non-word characters (\W), so it must be a word boundary

So only whole words are found, but not parts of words like in Instr.
My RegEx library of usable methods in VBA:
 

Josef P.

Well-known member
Local time
Today, 01:08
Joined
Feb 2, 2023
Messages
827
Try: [\[!."_']([Ff]orm1)[!."\s\]'] or (?:\b|Form_)[Ff]orm1\b .. Note: Form_Form1 not Forms_Form1
simple online test: https://regex101.com/

I let ChatGPT help me with (complex) RegExp patterns more and more often. It usually takes several attempts, but most of the time it works. Especially if you give examples and expected hits.
 
Last edited:

MajP

You've got your good things, and you've got mine.
Local time
Yesterday, 19:08
Joined
May 21, 2018
Messages
8,529
Thanks. I think I was overthinking it. Even if the search word begins or ends in a boundary (Me!, Docmd., Form_, etc) it still works. Only exception I find is if the user wanted to search for usage where the search word is entered using single or double quotes. They are looking for
reports("report1") but not reports!report1

They will just have to enter without quotes and get both back.
 

Users who are viewing this thread

Top Bottom