2012-03-30 52 views
2

我有一個關鍵字列表,並希望查看一個單元是否包含這些單詞中的任何一個。例如,如果我的關鍵字列表是(貓,狗,海龜),該功能將返回匹配,如果它正在看「狗先生魔術土地」。我發現了一個很好的UDF在線用作函數,但是當我嘗試循環它時,它會測試關鍵字列表中的每個單詞,我會得到#VALUE !.第一個函數是我的循環,第二個函數是在因特網上找到的UDF匹配函數(對不起,不記得在哪裏,但是支持誰的支持)。我嘗試過InStr等單詞匹配函數的變體。Excel中的循環詞匹配功能VBA

Function StringFind(rng(), source) 
For I = LBound(rng) To UBound(rng) 
StringFind = MyMatch(rng(I), source) 
If StringFind = "MATCH" Then Exit Function 
Next I 
StringFind = "NO MATCH" 
End Function 

Function MyMatch(FindText As String, WithinText As Variant) As String 
    ' 
    Dim vntFind As Variant 
    Dim vntWithin As Variant 

    For Each vntFind In Split(UCase(FindText), " ") 
     If Len(Trim(vntFind)) > 0 Then 
      For Each vntWithin In Split(UCase(WithinText), " ") 
       If Len(Trim(vntWithin)) > 0 Then 
        If vntFind = vntWithin Then 
         MyMatch = "MATCH" 
         Exit Function 
        End If 
       End If 
      Next 
     End If 
    Next 
    MyMatch = "NO MATCH" 
End Function 
+0

是的,我意識到它退出循環後,我不需要stringfind =「不匹配」的一部分,但它是一個想法... – postelrich 2012-03-30 13:45:50

回答

0

在VBE中原樣插入,我甚至無法編譯。

此行

StringFind = MyMatch(rng(I), source) 

需要改變,以

StringFind = MyMatch(rng(I).Value, source) 

,甚至得到它爲我工作。這可能是你的問題的原因。


編輯

好吧,我回顧了更詳細的全部。看起來這將適用於你。 (對不起,我不是故意要爲你做所有事情,而是在這裏)。它可能需要做一些調整才能滿足你的需求。

問題是您正在查找未定義的數據類型(添加/更改主要函數調用As StringAs Range)。雖然未定義的類型可以工作,但我認爲看到問題出現的原因令人困惑。我試圖在函數中設置一個斷點,並且因爲錯誤的數據類型被傳遞,所以從來沒有那麼遠。就我個人而言,我總是使用Option Explicit來幫助防止這樣的問題出現在我自己的代碼中。

下面的代碼現在將尋找在第一個參數的值(Search,可以是一個「」文本/ String或單個細胞/ Range)在第二個參數對所有值(Source一個Range組成的任一個或多個單元格)。

Public Function StringFind(Search As String, Source As Range) 
Dim rngCell As Range 
For Each rngCell In Source.Cells 
StringFind = MyMatch(Search, rngCell.Value) 
If StringFind = "MATCH" Then Exit Function 
Next rngCell 
StringFind = "NO MATCH" 
End Function 

Function MyMatch(FindText As String, WithinText As Variant) As String 
    ' 
    Dim vntFind As Variant 

    For Each vntFind In Split(UCase(FindText), " ") 
     If Len(Trim(vntFind)) > 0 Then 
      If vntFind = Trim(UCase(WithinText)) Then 
       MyMatch = "MATCH" 
       Exit Function 
      End If 
     End If 
    Next 
    MyMatch = "NO MATCH" 
End Function 
+0

THX,但並沒有幫助。仍然獲得#VALUE! :( – postelrich 2012-03-30 14:18:08

+0

感謝解決了! – postelrich 2012-03-30 17:57:19

+0

很高興聽到它,請接受答案,讓別人更容易找到它! – Gaffi 2012-03-30 18:02:14

3

1)FORMULA

我會先提供非VBA的解決了這個特殊的問題,因爲是不是真的需要VBA。這陣列公式將做同樣的事情。按CTRL-SHIFT-ENTER輸入數組,您將看到公式周圍出現花括號{}。然後你可以複製下來。

「= IF(OR(ISNUMBER(SEARCH($ F $ 1:$ F $ 3 A1))), 「匹配」, 「不匹配」)

2)UDF

使用與您的語法相同的語法,下面介紹如何使用UDF來處理這個問題。

enter image description here

Function MySearch(MyRNG As Range, MyStr As String) As String 
Dim cell As Range 

    For Each cell In MyRNG 
     If LCase(MyStr) Like LCase("*" & cell & "*") Then 
      MySearch = "Match" 
      Exit Function 
     End If 
    Next cell 

    MySearch = "No Match" 
End Function 
+0

+1爲好陣列配方 – 2012-03-30 15:27:39

+0

真棒非vba公式! – postelrich 2012-03-30 17:56:25