2015-03-02 139 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