例如,我们说我有以下单词和文字:
word = "bee"
text1 = "bla bla bee bla bla... "
text2 = "bla bla beep bla bla ..."
我希望第一个案例返回True,第二个案例返回False。
经过一段时间的搜索,我找到了一种方法,可以通过以下方式在文本中找到一个单词:
If Application.IsNumber(Application.Search(word, text1)) Then 'returns True
If Application.IsNumber(Application.Search(word, text2)) Then 'returns True
但两种情况都会返回True 是否有一种简单的方法(适用于任何单词和文本)来检查文本是否包含我正在寻找的单词,而不是其他单词中的单词?
答案 0 :(得分:0)
在前面和后面添加空格到每个输入,当vba有Instr时也不需要工作表函数:
Sub test()
Dim text1 As String
Dim word As String
word = "bee"
text1 = "bla bla beep bla bla... "
If InStr(" " & text1 & " ", " " & word & " ") > 0 Then
MsgBox "True"
Else
MsgBox "False"
End If
End Sub
答案 1 :(得分:0)
我的第一个想法是使用正则表达式(又名Regular Expression' s)。用你的话测试给出了要求的结果。带有前缀和后缀的\b
表示这些字符是边界锚,它们开始和结束单词。这个词字面上是bee
,区分大小写。您使用regex.IgnoreCase = True
使其不区分大小写。
Sub Testing()
Dim word As String
word = "bee"
Dim isFound As String
isFound = "bla bla bee bla bla... "
Dim isNotFound As String
isNotFound = "bla bla beep bla bla ..."
Debug.Print IsWordFound(word, isFound)
Debug.Print IsWordFound(word, isNotFound)
End Sub
Public Function IsWordFound(ByVal wordToFind As String, ByVal textToSearch As String) As Boolean
'Requires Tools>References>Microsoft VBScript Regular Expressions 5.5 to be checked
Dim regex As VBScript_RegExp_55.RegExp
Set regex = New RegExp
regex.Pattern = "\b" & wordToFind & "\b"
IsWordFound = regex.Test(textToSearch)
End Function