比较文本,如果更短

时间:2014-05-26 09:25:23

标签: excel vba

我正在对excel字符串和单词字符串(在段落中)进行comparmision,删除所有特殊字符froom excel字符串和我正在做的字符串比较。 Unformtunetly循环遍历单词paragrapphs并寻找特定的匹配字符串excel有完整的字符串可以找到,但有时不是单词:

找到excel字符串:

Kodpocztowyimiejscowo34331winna

例如搜索段落:

Ulicaulywiecka29Kodpocztowyimiejscowo34331winn ' missing 'a' in the end ...

我的比较代码在这种情况下不适用于此行:

  

如果是InStr(txt,搜索)那么

Unformtunetly有时单词可以剪掉一些字母,你知道我如何更新我的代码以保证那些情况下的安全吗?看到我的全部代码:

 Do
         ExcelField = ""
         X = X + 1
         ExcelField = EWS.Cells(RowNr, X)

         If ExcelField <> "" Then

         ExcelField = RemoveSpecialChars(ExcelField)

             If ExcelField = "KONIEC" Then Exit Do

 Dim search As String
     search = ExcelField

     Dim para As Paragraph

     For Each para In WordDoc.Paragraphs

         Dim txt As String
         txt = para.Range.Text  'whole word paragraphs
         txt = RemoveSpecialChars(txt) ' whole paragraph withhout special characters

         If txt <> "" Then    'sometimes in Excel columns are nulls we go next
         If InStr(txt, search) Then       

             EWS.Cells(5, X).Interior.ColorIndex = 4  'green marked
             Exit For 'field found in word exit and next
         Else
             EWS.Cells(5, X).Interior.ColorIndex = 3  'red marked '                                Exit For 'field found in word exit and next

         End If
         End If

     Next

         End If

     Loop Until EWS.Cells(RowNr, X) = "KONIEC"

1 个答案:

答案 0 :(得分:0)

您需要确定文本左侧必须匹配的字符数。因此,如果你决定20,那么就足够了,然后使用:

If InStr(txt, Left(search,20)) Then

对于不区分大小写的比较:

If InStr(1, txt, Left(search,20), vbTextCompare) Then

例如,您可以检查前x个字符,但将其基于搜索字符串的原始长度。例如,

If Len(search) > 20 Then
    search = Left(search, 20) 'ignore after 20th character
ElseIf Len(search) > 10 Then
    Left(search, Len(search)-3) 'ignore last 3 characters
End If

您需要尝试为您的案例找到合适的逻辑。