InStr返回ENTIRE标准而不是partials

时间:2014-03-03 21:47:29

标签: excel-vba vba excel

下面的代码不会从名称列表中返回EXACT值。例如,如果在列表中我有:

安 安娜 汉娜

......我正在寻找" Hannah Fawler"代码将返回以下内容:

" Ann,Anna,Hannah"

我需要更新代码以在单元格中查找整个名称(Hannah)(将有注释并将提及人名)并返回没有部分的整个名称(Hannah> Hannah)。有谁知道怎么做?

Public Function NameLister(r1 As Range, r2 As Range) As String
    Dim Sentence As String
    NameLister = ""
    Sentence = LCase(r2.Text)
    For Each r In r1
        v = LCase(r.Text)
        If v <> "" Then
            If InStr(1, Sentence, v) > 0 Then
                If NameLister = "" Then
                    v = StrConv(v, vbProperCase)
                    NameLister = v
                Else
                    v = StrConv(v, vbProperCase)
                    NameLister = NameLister & ", " & v
                End If
            End If
        End If
    Next r
End Function

1 个答案:

答案 0 :(得分:1)

这是一个使用VBScript正则表达式对象的解决方案。它通过要求名称出现在单词边界内(正则表达式中为\b)来匹配整个名称(无部分)。

Public Function NameLister(r1 As Range, r2 As Range) As String
    Dim Sentence As String, rgx As Object
    NameLister = ""
    Sentence = LCase(r2.Text)
    'Initialize regular expression object
    Set rgx = CreateObject("vbscript.regexp")
    For Each r In r1
        v = LCase(r.Text)
        If v <> "" Then
            'Set search pattern to match only entire word.
            rgx.Pattern = "\b" & v & "\b"
            'Test Sentence for matches
            If rgx.Test(Sentence) Then
                If NameLister = "" Then
                    v = StrConv(v, vbProperCase)
                    NameLister = v
                Else
                    v = StrConv(v, vbProperCase)
                    NameLister = NameLister & ", " & v
                End If
            End If
        End If
    Next r
End Function