在Excel VBA中循环词匹配function

我有一个关键字列表,并希望看到一个单元格是否包含这些单词中的任何一个。 例如,如果我的关键字列表是(猫,狗,龟),该function将返回匹配,如果它正在寻找“狗先生魔术土地”。 我已经find了一个很好的UDF在线使用作为function,但是当我尝试循环它,所以它testing我的关键字列表中的每个字我得到#VALUE !. 第一个函数是我的循环,而第二个是在互联网上find的UDF匹配函数(抱歉,不记得在哪里,但道具谁做的。)我已经尝试了单词匹配函数的变体,如InStr无济于事。

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 

把它插在我的VBE中,我甚至不能编译。

这条线

 StringFind = MyMatch(rng(I), source) 

需要改变

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

甚至让它为我工作。 这可能是你的问题的原因。


编辑

好的,我更详细地回顾了一下。 看起来这样会适合你。 (对不起,我不是故意要为你做这一切,但在这里。)它可能需要更多的调整,使其满足您的需求。

问题是你正在寻找未定义的数据types(添加/更改主函数调用为As StringAs Range )。 虽然未定义的types可以工作,但我认为这个问题出现的原因很混乱。 我试图在函数中设置一个断点,因为错误的数据types被传递,所以从来没有得到那么远。 就个人而言,我总是使用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 

1)配方

我会首先提供非VBA解决scheme来解决这个问题,因为VBA并不是真的需要。 这个数组公式会做同样的事情。 通过按下CTRL-SHIFT-ENTER来input数组,你会看到花括号{}出现在你的公式周围。 那么你可以复制下来。

'= IF(OR(ISNUMBER(SEARCH($ F $ 1:$ F $ 3,A1))),“Match”,“No Match”)

2)UDF

使用与你的相同的语法,这里是我可以用UDF来处理这个问题。

在这里输入图像说明

 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