【问题标题】:Find word (but not inside another word) in a text w/ VBA在带有 VBA 的文本中查找单词(但不在另一个单词中)
【发布时间】:2018-05-09 00:33:05
【问题描述】:

例如,假设我有以下单词和文本:

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。
有没有一种简单的方法(适用于任何单词和文本)来检查文本是否包含我正在寻找的单词,但不包含在其他单词中?

【问题讨论】:

  • 当然。检查上述代码的结果是否有空格或标点符号。
  • 这是个好主意@nicomp!但是如果单词是文本中的第一个或最后一个单词,有什么方法可以找到它吗?
  • 当然有。边界条件没问题。

标签: string vba


【解决方案1】:

在每个输入的前后添加空格,当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

【讨论】:

    【解决方案2】:

    我的第一个想法是使用正则表达式(又名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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多