2015-03-02 195 views
0

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

但是,如果下面给出的单词退出就是例子,函数或宏应该忽略它们。

Column1 \t   Column2 \t   Result \t Expected Result 
 
Spider-Man \t  SpiderMan 56 \t  TRUE \t  TRUE 
 
6x \t    6x25 \t    TRUE \t  TRUE 
 
jesse james \t  jesse/james \t   TRUE \t  TRUE 
 
13.3" \t   133 hd \t    FALSE \t TRUE 
 
15.6" \t   5517 156 ccfl \t  FALSE \t TRUE 
 
United States \t United States Brands FALSE \t TRUE 
 
United States \t UnitedStates Brands \t FALSE \t TRUE 
 
United States \t United-States Brands FALSE \t TRUE 
 
Force \t   Air "Force" One \t  FALSE \t TRUE 
 
Force \t   Air Force-One \t  FALSE \t 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

是否有任何其他的方式来实现我的目标?

+0

你现在的代码有什么问题? – 2015-03-02 14:33:03

+0

@ Gary'sStudent好心检查我的例子,我无法得到预期的结果 – Linga 2015-03-02 19:02:54

回答

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

它看起来应该也剥离空间 - 例如案例'美国品牌'...为什么模式不仅仅是[[0-9a-zA-Z]',然后用''“''替换? – Captain 2015-03-02 14:54:25

+0

谢谢..我以为我疯了,想知道为什么空间也没有被替换掉。我的正则表达式是生锈的,我需要更多的咖啡。我已经用补充说明修复了它。 – JNevill 2015-03-02 15:04:19

+0

@JNevill你的formu;一个和正则表达式很酷。但是“= NOT(ISERROR(FIND(StripNonAlpha(A1),StripNonAlpha(B1))))”公式是区分大小写的。我想它作为非区分大小写例如:Spiderman = SpiderMan – Linga 2015-03-02 18:53:41