2017-12-19 13 views
1

문자열 문장 : 연결, 수도,VBA - 문자열 문장 목록에서 단어를 포함하는 경우 확인

에서

의사 코드 :

말씀 사전 "서로 문서를 연결했을 수 있습니다"

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

단어 목록과 문장 비교는 대소 문자를 구분하지 않아야합니다. 속성이있는 개체를 만들고 exists을 사용하려고 시도했지만 잘못된 검색 결과가 나타납니다. 아마도 단어 대소 문자 때문에.

+0

: 어떻게 당신이 당신의 배열을 생성하는 것은 당신에게 달려 있지만, 여기에 예입니다 |에서) \ b 참조 : https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops –

답변

2

트릭은 단어 사전을 분할하고 분할 된 항목을 하나씩 검색하는 것입니다. 하나라도 발견되면 부울 hasWordTrue으로 변경됩니다. 그런 다음이 부울 값을 기준으로 올바른 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

5 월 'hasWord'가'True'이면'Exit For', 어떤 단어가 포함되어 있는지 신경 쓰지 않으면 실행 속도가 빨라집니다. – Greedo

+0

@Greedo -'OP'가 코드를 너무 많이 남용하여 Exit For가 실행하면, 그는 느린 코드를받을 자격이 있습니다. :)하지만 일반적으로 추가하는 것이 좋습니다. – Vityata

+0

매력처럼 작동했습니다. 매우 감사! – user3704920

1

Array을 사용하고 Instr 기능을 사용할 수 있습니다. 수도 | * 단어에 대처하는 가장 좋은 방법 * 잘못된 문자열 일치를 방지하고 정규식 \ (B)가 (연결된 문장 부호를 다루는 IMO

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 
+0

단어 단위가 아닌 모든 단어에 대한 작업 상태가 필요합니다. 예 : '목록에있는 단어를 포함하고 있지 않습니다. '또는'단어를 포함하고 있습니다.' – Vityata