【问题标题】:Excel VBA - increase accuracy of Match functionExcel VBA - 提高匹配功能的准确性
【发布时间】:2013-06-23 01:32:51
【问题描述】:

我在我的程序中使用了一个 Match 函数,它的主要目的是比较用户输入的输入,然后循环到数据库中,并在每次匹配时执行一些操作。

目前,我正在处理这个:

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

然后当它被使用时:

If Match(sCurrent.Range("A" & i).Value, cell.Value) Then

这是我的问题:

这太不准确了。如果我的数据库中有“Foxtrot Hotel”,只要用户键入“F”“Fo”“Fox”“ox”“xtro”“t hot”等等,这个函数就会找到一个匹配,所以只要有一个字符串包含在完整句子中的字符。

我想要的是让我的 Match 函数只识别完整的单词。因此,在这种情况下,仅显示三个特定案例的匹配项:“Foxtrot”“Hotel”和“Foxtrot Hotel”。

我已经阅读了一个名为“lookat”的属性,它可以使用 Find 函数 (lookat:=xlwhole) 执行此类操作,您知道是否可以在我的 Match 函数中插入类似的东西吗?

谢谢!

【问题讨论】:

  • Cell.value 是否包含您的数据库?以及以什么形式 - 用逗号等分隔的单词?
  • 一方面,您只有一个单词(在 Range("A" & i) 中),另一方面,在 Cell.Value 中,您有单词或连续单词,主要由空间(可以是“Foxtrot”、“Hotel Foxtrot”或“Capital Building Center”等)。我会尝试你建议的答案,谢谢@brettdj!

标签: excel match vba


【解决方案1】:

您可以像这样使用。这个只对整个单词进行不区分大小写的匹配(使用正在搜索的单词周围的单词边界)。

  • 假(fo后面是一个字母,不是单词边界)
  • 是的
  • 是的
  • 错误(FOXTROT h 后面没有单词边界)

Find 不适用于您的 xlWhole - 这将看起来匹配整个单元格内容,而不是内容中的单个单词。

Function WordMatch(searchStr As Variant, matchStr As Variant) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\b" & matchStr & "\b"
.ignorecase = True
WordMatch = .test(searchStr)
End With
Set objRegex = Nothing
End Function

Sub B()
Debug.Print WordMatch("foxtrot hotel", "fo")
Debug.Print WordMatch("foxtrot hotel", "hotel")
Debug.Print WordMatch("foxtrot hotel", "FOXTROT")
Debug.Print WordMatch("foxtrot hotel", "FOXTROT h")
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多