VBA - 检查字符串句子是否包含列表中的任何单词

时间:2017-12-19 16:11:31

标签: vba dictionary match

字符串句子:“可能已将文档链接到另一个”

单词词典:链接,可以,来自

伪代码

If StringSentence containsAny(wordDictionary) Then
     MsgBox "contains a word"
Else
     MsgBox "doesn't containt any word from list"
End If

从单词列表到句子的比较应该不区分大小写。我尝试使用属性创建一个对象并使用exists,但我得到误报。也许是因为套管这个词。

2 个答案:

答案 0 :(得分:2)

诀窍是分割wordDictionary并搜索每个分割项目。如果找到一个,则布尔hasWord更改为True。然后,根据此布尔值,给出正确的MsgBox文本:

Sub TestMe()

    Dim sentence        As String
    Dim wordDictonary   As String

    Dim myArray         As Variant
    Dim cnt             As Long
    Dim hasWord         As Boolean

    sentence = "may have linked documents from another"
    wordDictonary = "linkeD, mAy, From "    
    sentence = LCase(sentence)
    wordDictonary = LCase(wordDictonary)        
    myArray = Split(wordDictonary, ",")

    For cnt = LBound(myArray) To UBound(myArray)
        If InStr(1, sentence, Trim(myArray(cnt))) Then hasWord = True : Exit For
    Next cnt

    MsgBox (IIf(hasWord, "Contains a word", "Does not contain a word!"))

End Sub

要忽略大小写字母,sentencewordDictionary变量会小写LCase

答案 1 :(得分:1)

您可以使用Array并使用Instr功能。你如何创建阵列取决于你,但这是一个例子:

Public Sub Test()
  Dim sArray() As Variant
  Dim sSentence As String
  Dim s As Variant
  Dim sDict as String
  sDict = "linked, may, from"

  sSentence = "may have linked documents from another"
  sArray = Split(sDict,",")

  For Each s In sArray
    If InStr(1, sSentence, Trim$(s), VbCompareMethod.vbTextCompare) > 0 Then
      MsgBox ("'" & s & "' was found.")
    Else
      MsgBox ("'" & s & "' was NOT found.")
    End If
  Next

End Sub