ms-accessvba

Splitting a full name string into First, Last and Middle Initial in VBA Access


First off apoligies, I am completely new to coding in VBA for Access, so there are probably a lot of errors. but anyways, I'm having a bit of issues with the first name and that middle initial. Currently the names are formatted as a string in [lastName, firstName middleInitial] I have 3 text boxes that are labled lastName firstName and middleInitial. What the below code should do is separate that string into the three approrpriate boxes but it gets hung up on the first name, where it doesn't know how to stop at the space or it cuts off a few characters, and the middle initial where it only works if they have a middle initial, but is throwing an error if it doesnt find one. I've been tearing my hair out trying to figure it out, and thus I have come to an impass and am asking here.

Thank you very much!

Private Sub cbxMbr_AfterUpdate()

    If Not Me.opgMngRoster.Value = 1 Then
        'Member's Last Name
        Dim lastName As String
        lastName = Left(cbxMbr.Text, (InStr(1, cbxMbr.Text, ",") - 1))
        Me.txtLastName.Value = lastName

        'Member's First Name
        Dim firstName As String
        firstName = Mid(cbxMbr.Text, InStr(1, cbxMbr.Text, " "), (Len(cbxMbr.Text) - InStr(1, cbxMbr.Text, " ")))
        Me.txtFirstName.Value = firstName

        'Member's Middle Initial
        Dim midName As String
        midName = Mid(cbxMbr.Text, InStr(InStr(1, cbxMbr.Text, " ") + 1, cbxMbr.Text, " "))

        If midName = vbNullString Then
            Me.txtMidInit.Value = " "
        Else
            Me.txtMidInit.Value = midName
        'DoCmd.RunSQL "SELECT MEMBER ROSTER WHERE "
        End If
    End If

End Sub

Solution

  • You can use Split:

    ' "Duck, Donald D."
    ' "Duck, Donald"
    
    Me!txtLastName.Value = Split(Me!cbxMbr.Value, ",")(0)
    ' Duck
    
    Me!txtFirstName.Value = Split(Trim(Split(Me!cbxMbr.Value, ",")(1)), " ")(0)
    ' Donald
    
    Me.txtMidtInit.Value = Split(Trim(Split(Me!cbxMbr.Value, ",")(1)) & " ", " ")(1)
     ' D. or zero-length string.