The following uses a regex to do the removal. It has an additional regex pattern at the end to get rid of excessive white space left behind.
The list of words to remove is passed as a comma separated list without white space. Inside the regex function this is converted to a pattern of, in this case, \b(in|for|a)\b
. This is essentially an OR list of individual words i.e. either "in", "for" or "a"
.
There is an optional 3rd parameter that allows you to choose whether to ignore the case of the matched words. It defaults to False
.
You can use it in the sheet as an UDF.
VBA:
Option Explicit
Public Sub test()
Dim j As Long, arr()
arr = Array("hello include in the formula for attachment a dog")
For j = LBound(arr) To UBound(arr)
Debug.Print RemoveUnWantedStrings(arr(j), "in,for,a", False)
Next
End Sub
Public Function RemoveUnWantedStrings(ByVal inputString As String, ByVal sPattern As String, Optional ignoreCase As Boolean = False) As Variant
Dim matches As Object, iMatch As Object
With CreateObject("vbscript.regexp")
.Global = True
.MultiLine = True
.ignoreCase = ignoreCase
.Pattern = "\b(" & Replace$(sPattern, ",", "|") & ")\b"
If .test(inputString) Then
' Set matches = .Execute(inputString)
'For Each iMatch In matches
inputString = .Replace(inputString, vbNullString)
' Next iMatch
Else
RemoveUnWantedStrings = inputString
Exit Function
End If
.Pattern = "\s{2,}"
RemoveUnWantedStrings = .Replace(inputString, Chr$(32))
End With
End Function
In sheet UDF:

Regex: Try it here.
/
\b(in|for|a)\b
/
gm
\b
assert position at a word boundary (^\w|\w$|\W\w|\w\W)
1st Capturing Group (in|for|a)
1st Alternative in
in
matches the characters in
literally (case sensitive)
2nd Alternative for
for
matches the characters for
literally (case sensitive)
3rd Alternative a
a
matches the character a
literally (case sensitive)
\b
assert position at a word boundary (^\w|\w$|\W\w|\w\W)