Excel – VBA:使匹配方法的限制更less(通过查找一个句子中的单词)

我正在使用我的Excel程序中的匹配function,但我有一个问题,因为它只select相同的匹配 。 例如,如果您将一个“香蕉”细胞与另一个“香蕉”细胞进行比较,就会发挥作用并返回一个正值。
但如果你把“香蕉”与一个内容是“香蕉巧克力”的单元相比,那么它就不会认识到香蕉这个词在单元格中。

就我而言,每当一个单词出现在句子中时,我想返回一个TRUE值。

这是我的代码:

Worksheets("sBldgMakati").Activate For i = 2 To 605 Range("B" & i).Activate myResult = IsNumeric(Application.Match(ActiveCell.Value, elementsListRange, 0)) If myResult Then Range("K" & i).Value = Range("K" & i).Value + 10 Else Range("K" & i).Value = Range("K" & i).Value + 0 End If Next i 

我必须指定在这个代码中, elementsListRange对应于一个单元格的范围,其内容只有一个单词(例如“Banana”), ActiveCell.value通常是一个较长的expression式(例如“Banana choco”)。

在此先感谢您的帮助 !

使用下面的函数,它匹配一个string中的子string:

 Function match(searchStr As Variant, matchStr As Variant) As Boolean match = False If (IsNull(searchStr) Or IsNull(matchStr)) Then Exit Function If (matchStr = "") Or (searchStr = "") Then Exit Function Dim f As Variant f = InStr(1, CStr(searchStr), CStr(matchStr), vbTextCompare) If IsNull(f) Then Exit Function match = f > 0 End Function 

要使用范围:

 Dim searchstr="A Banana found" Dim isFound as boolean IsFound=false For each c in range If match(searchstr, c.value) IsFound=true Exit for End if End for 

请注意searchStrmatchStr是不同的,所以您可以将Excel单元格中的值传递给它。

从Excel中的帮助文档(如果您按F1并searchmatch ):

如果match_type为0且lookup_value是文本string,则可以在lookup_value参数中使用通配符(问号(?)和星号(*))。 一个问号匹配任何单个字符; 星号匹配任何字符序列。

因此,如果C8包含"Banana choco"=MATCH("*Banana*",C8,0)返回1

在VBA中,如果要匹配的项目位于单元格中,则可以使用string连接来包含通配符星号,例如:

 myResult = IsNumeric(Application.Match("*" & ActiveCell.Value & "*", elementsListRange, 0)) 

如果在B2:B605范围内有很多句子要对照B2:B605中的所有单词进行testing,就像在这种情况下出现的情况一样,我认为你可能需要做这样的事情(未经testing):

 For Each cell in elementsListRange.Cells myResult = Application.Match("*" & cell.Value & "*", B2:B605, 0) if (IsNumeric(myResult)) then Range("K" & myResult).Value = Range("K" & myResult).Value + 10 end if next