如何在Excel VBA函数中允许通配符*在string中查找单词?

我有以下function,find一个string中的单词,例如寻找唐将find唐而不是不是我想要的:“我不知道唐,你怎么看?

然而我也发现我需要寻找像种族,种族,赛车这样的词汇。 我希望能够searchrac *来覆盖所有这些变体,而不是search每个变体。

是否有可能更新代码来做到这一点? 还是有人有任何代码可以解决这个问题?

Function InStrExact(Start As Long, SourceText As String, WordToFind As String, _ Optional CaseSensitive As Boolean = False) Dim x As Long, Str1 As String, Str2 As String, Pattern As String If CaseSensitive Then Str1 = SourceText Str2 = WordToFind Pattern = "[!A-Za-z0-9]" Else Str1 = UCase(SourceText) Str2 = UCase(WordToFind) Pattern = "[!A-Z0-9]" End If For x = Start To Len(Str1) - Len(Str2) + 1 If Mid(" " & Str1 & " ", x, Len(Str2) + 2) Like Pattern & Str2 & Pattern _ And Not Mid(Str1, x) Like Str2 & "'[" & Mid(Pattern, 3) & "*" Then InStrExact = x Exit Function End If Next End Function 

一个简单的修改是在searchstring的末尾添加一个通配符,并匹配原始string中的所有剩余字符。 改变是取代这一行:

 If Mid(" " & Str1 & " ", x, Len(Str2) + 2) Like Pattern & Str2 & Pattern _ 

有了这个:

 If Mid(" " & Str1 & " ", x) Like Pattern & Str2 & Pattern & "*" _ 

这只是删除了要匹配的字符数量的限制。 如果将通配符添加到search词的末尾,则会出现在尾随模式之前,因此可以添加任意数量的附加字符。 如果search词中没有通配符,则尾随模式仍然需要在search词之后立即出现,因此仍然需要精确匹配。

请注意,如果您正在search的单词是最后一个单词,并且您添加了通配符,则会出现问题。 Str2的长度会导致函数停止search太快。 所以完整的解决scheme是也取代这一行:

  For x = Start To Len(Str1) - Len(Str2) + 1 

有了这个:

  For x = Start To Len(Str1) 

没有必要停止检查任何更早的。

我会去如下:

 Function InStrExact(startPos As Long, sourceText As String, wordToFind As String, _ Optional CaseSensitive As Boolean = False) As Long Dim x As Long Dim actualSourceText As String, actualWordToFind As String, Pattern As String Dim word As Variant actualSourceText = Replace(Mid(sourceText, startPos), ",", "") If CaseSensitive Then Pattern = "[A-za-z]" Else actualSourceText = UCase(actualSourceText) actualWordToFind = UCase(wordToFind) Pattern = "[AZ]" End If For Each word In Split(actualSourceText, " ") If CStr(word) Like actualWordToFind & Pattern Or CStr(word) = actualWordToFind Then InStrExact2 = x + 1 Exit Function End If x = x + Len(word) + 1 Next InStrExact = -1 '<--| return -1 if no match End Function