在一个句子中找到单词

时间:2015-03-02 14:05:52

标签: excel excel-vba vba

我在一个有句子的单元格中找到一个单词,包括句子和句子。要找到的单词可能有空格/特殊字符。

但是函数或宏应该忽略它们&如果下面给出的单词exits是示例,则匹配它。

Column1	         Column2	           Result	Expected Result
Spider-Man	     SpiderMan 56	       TRUE	    TRUE
6x	             6x25	               TRUE	    TRUE
jesse james	    jesse/james	           TRUE	    TRUE
13.3"	        133 hd	               FALSE	TRUE
15.6"	        5517 156 ccfl	       FALSE	TRUE
United States	United States Brands   FALSE	TRUE
United States	UnitedStates Brands	   FALSE	TRUE
United States	United-States Brands   FALSE	TRUE
Force	        Air "Force" One	       FALSE	TRUE
Force	        Air Force-One	       FALSE	TRUE

在上面的示例中,我正在使用以下功能但尚未获得所需的结果。

Function ExactString(Text As String, Word As String) As Boolean
a = Module1.StripNonAlpha(Text)
b = Module1.StripNonAlpha(Word)
     'ExactString = " " & UCase(a) & " " Like "*[!A-Z]" & UCase(b) & "[!A-Z]*"
     If InStr(1, a, b, 1) Then
     ExactString = True
     Else
     ExactString = False
     End If
End Function
-----------------------------------------------------------------
Function StripNonAlpha(TextToReplace As String) As String
Dim ObjRegex As Object

Set ObjRegex = CreateObject("vbscript.regexp")
With ObjRegex
.Global = True
.Pattern = "[^a-zA-Z\s]+"
StripNonAlpha = .Replace(Replace(TextToReplace, "-", Chr(32)), vbNullString)
StripNonAlpha = Module1.CleanSpace(StripNonAlpha)
End With
End Function
----------------------------------------------------------------
Function CleanSpace(ByVal strIn As String) As String
    strIn = Trim(strIn)

  ' // Replace all space pairings with single spaces
    Do While InStr(strIn, " ")
        strIn = Replace(strIn, " ", "")
        strIn = Replace(strIn, "  ", "")
    Loop

    CleanSpace = strIn
End Function

有没有其他方法可以实现我的目标?

1 个答案:

答案 0 :(得分:1)

更改第二个函数中的REGEX以允许数字和删除空格,因为这对您的情况来说似乎很重要。您可以删除第三个功能,因为它是多余的。

Function StripNonAlpha(TextToReplace As String) As String
    Dim ObjRegex As Object

    Set ObjRegex = CreateObject("vbscript.regexp")
    With ObjRegex
        .Global = True
        .Pattern = "[^0-9a-zA-Z]+"
        StripNonAlpha = .Replace(TextToReplace, vbNullString)
    End With
End Function

您还可以删除第一个函数,因为它可以通过工作表公式轻松处理,这应该会减少开销。在工作表中,假设A列和B列是您要比较的两个,那么在C列中:

=NOT(ISERROR(FIND(StripNonAlpha(A1),StripNonAlpha(B1))))