使用VBA从具有后缀的范围中提取姓氏

时间:2015-05-14 11:21:14

标签: vba excel-vba excel

我在列中有一个全名列表,例如:

Dave M. Butterworth
Dave M. Butterworth,II
H.F. Light jr
H.F. Light ,jr.
H.F. Light sr 
Halle plumerey

名称在一列中。首字母不仅限于这些。

我想使用通用函数提取姓氏。有可能吗?

2 个答案:

答案 0 :(得分:0)

考虑以下 UDF

Public Function LastName(sIn As String) As String
  Dim Ka As Long, t As String
  ary = Split(sIn, " ")
  Ka = UBound(ary)
  t = ary(Ka)

  If t = "jr" Or t = ",jr" Or t = "sr" Or t = ",jr." Then
    Ka = Ka - 1
  End If

  t = ary(Ka)
  If InStr(1, t, ",") = 0 Then
    LastName = t
    Exit Function
  End If

  bry = Split(t, ",")
  LastName = bry(LBound(bry))
End Function

enter image description here

<强> 注:

您必须扩展此行:

If t = "jr" Or t = ",jr" Or t = "sr" Or t = ",jr." Then

包含您要排除的所有其他初始集。
您还必须更新此代码以便在找到它们时处理其他异常!

答案 1 :(得分:0)

删除标点符号,拆分为数组并向后走,直到找到与“ii / jr / sr / dr”等可忽略标记的查找不匹配的字符串。

您还可以根据长度添加支票以消除令牌。

Function LastName(name As String) As String
    Dim parts() As String, i As Long
    parts = Split(Trim$(Replace$(Replace$(name, ",", ""), ".", "")), " ")

    For i = UBound(parts) To 0 Step -1
        Select Case UCase$(parts(i))
            Case "", "JR", "SR", "DR", "I", "II"
            Case Else:
                LastName = parts(i)
                Exit Function
        End Select
    Next
End Function