ExtractFirstAndLastName – Extracting the first/last name from a string will the full name

' Extract the first and last name from a string will the full name.' The routine handles the "LastName, FirstName" and "FirstName LastName" ' formats, and returns the first and last name with byref output parameters.'' Example:'    Dim firstName, lastName As String'    ExtractFirstAndLastName("Marco", firstName, lastName)'    Debug.WriteLine("FirstName=" & firstName & " " & "LastName=" & lastName)'    ExtractFirstAndLastName("Marco Bellinaso", firstName, lastName)'    Debug.WriteLine("FirstName=" & firstName & " " & "LastName=" & lastName)'    ExtractFirstAndLastName("Bellinaso, Marco", firstName, lastName)'    Debug.WriteLine("FirstName=" & firstName & " " & "LastName=" & lastName)Sub ExtractFirstAndLastName(ByVal fullName As String, ByRef firstName As String, _    ByRef lastName As String)    firstName = ""    lastName = ""    ' if the fullname has a comma, it considers the     ' "LastName, FirstName" format, and     ' "FirstName LastName" otherwise    Dim commaPos As Integer = fullName.IndexOf(",")    If commaPos > -1 Then        lastName = fullName.Substring(0, commaPos).Trim()        firstName = fullName.Substring(commaPos + 1).Trim()    Else        ' find the space        Dim spacePos As Integer = fullName.IndexOf(" ")        ' if the space is not found, consider         ' everything as first name, otherwise do the split        If spacePos = -1 Then            firstName = fullName        Else            firstName = fullName.Substring(0, spacePos).Trim()            lastName = fullName.Substring(spacePos).Trim()        End If    End IfEnd Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: