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

问题描述 投票:1回答:2

字符串句子:“可能有来自另一个的链接文件”

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

伪代码:

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

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

vba dictionary match
2个回答
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
投票

你可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.