示例价值:Becky G Smith
我已经可以获得A列中每个人的名字,并将结果放在B列中:
For i = 2 To lastrow
x = InStr(1, Cells(i, "A").Value, " ")
y = InStr(1, Cells(i, "A").Value, "@")
If InStr(1, Cells(i, "A").Value, " ") > 0 Then
Cells(i, "B").Value = Left(Cells(i, "A"), x - 1)
ElseIf InStr(1, Cells(i, "A").Value, "@") > 0 Then
Cells(i, "B").Value = Left(Cells(i, "A"), y - 1)
End If
Next i
ElseIf InStr(1, Cells(i, "A").Value, "@") > 0 Then
声明存在,因为有时我会处理电子邮件,例如Becky@gmail.com
问题在于"史密斯"作为她的姓氏。我不想要中间的首字母。为了得到姓氏,我试过这个:
For i = 2 To lastrow
w = InStr(1, Cells(i, "A").Value, " ")
x = InStr(w, Cells(i, "A").Value, " ")
y = InStr(1, Cells(i, "A").Value, "@")
Z = Len(Cells(i, "A").Value)
If InStr(1, Cells(i, "A").Value, " ") > 0 Then
Cells(i, "C").Value = Right(Cells(i, "A"), Z - x)
ElseIf InStr(1, Cells(i, "A").Value, "@") > 0 Then
Cells(i, "C").Value = Right(Cells(i, "A"), Z - y)
End If
Next i
但最终w
中的x = InStr(w, Cells(i, "A").Value, " ")
会出现错误。显然VBA认为w
等于0.所以我需要一种在第二个空格之后提取文本的方法。
答案 0 :(得分:2)
试试这个:
Public Function GetLastName(sName As String) As String
Dim aWords() As String
aWords = Split(sName, " ")
GetLastName = aWords(UBound(aWords))
End Function
您可以在工作表中使用它