+ Reply to Thread
Results 1 to 19 of 19

rearrange first last and middle name in a cell

Hybrid View

  1. #1
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    rearrange first last and middle name in a cell

    Hey all,

    Basically I have one cell that can look like this:

    IN RIGHT OF AKA PAUL A HERMAN,

    And I want to have it look like this:

    HERMAN PAUL A

    So:

    1) extract content to right of AKA
    2) If comma exists at end, remove it
    3) Rearrange the name so it's last, first, middle rather than first, middle, last

    I have been working on this and this is what I have:

    Sub Inspect()
        Dim old_str As String
        Dim new_str As String
        Dim first_name As String
        Dim last_name As String
        Dim middle_name As String
        Dim regex As Object
        Dim Rng As Range
        
        pos = InStr(Range("A1"), "AKA")
        
        If pos <> 0 Then
               old_str = Right(Range("A1"), Len(Range("A1")) - pos - 2)
        End If
        
        new_str = Left(old_str, Len(old_str) - 1)
        
        Range("B1").Value = Trim(new_str)
        
        Set Rng = Range("B1")
    
        Set regex = CreateObject("VBScript.RegExp")
    
        regex.Global = True
        regex.IgnoreCase = True
        regex.Pattern = "(^\w+\s\w+\s\w+)"
    
        If regex.Test(Range("B1").Value) Then
        
            first_name = Left(B1, Find(" ", B1) - 1)
            
            middle_name = Mid(B4, Find(" ", B4) + 1, Find(" ", B4, 1 + Find(" ", B4)) - Find(" ", B4) - 1)
        
            last_name = Right(A1, Len(A1) - Find("*", Substitute(A1, " ", "*", Len(A1) - Len(Substitute(A1, " ", "")))))
        End If
        
        Range("C1").Value = last_name & " " & first_name & " " & middle_name
    End Sub
    I get compiler error and it highlights the FIND function. It appears I cannot use excel formulas in a VBA script. Anyone have any solution how I can extract the first, last, and middle so I can rearrange them in my VBA function?

    Thanks for response

  2. #2
    Forum Expert tigeravatar's Avatar
    Join Date
    03-25-2011
    Location
    Colorado, USA
    MS-Off Ver
    Excel 2003 - 2013
    Posts
    5,361

    Re: rearrange first last and middle name in a cell

    johnmerlino,

    Find is a worksheet function, so to use it in VB, it has to be prefaced with WorksheetFunction. like so:

    WorksheetFunction.Find( 'Place Find function here


    Hope that helps,
    ~tigeravatar

  3. #3
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    Thanks for response. I did as you suggested and I now get the error "Unable to get the find property of the worksheetfunction class":

    Sub Inspect()
        Dim old_str As String
        Dim new_str As String
        Dim first_name As String
        Dim last_name As String
        Dim middle_name As String
        Dim regex As Object
        Dim Rng As Range
        
        pos = InStr(Range("A1"), "AKA")
        
        If pos <> 0 Then
               old_str = Right(Range("A1"), Len(Range("A1")) - pos - 2)
        End If
        
        new_str = Left(old_str, Len(old_str) - 1)
        
        Range("B1").Value = Trim(new_str)
        
        Set Rng = Range("B1")
    
        Set regex = CreateObject("VBScript.RegExp")
    
        regex.Global = True
        regex.IgnoreCase = True
        regex.Pattern = "(^\w+\s\w+\s\w+)"
    
        If regex.Test(Range("B1").Value) Then
        
            first_name = Left(B1, WorksheetFunction.Find(" ", B1) - 1)
            
            middle_name = Mid(B4, WorksheetFunction.Find(" ", B4) + 1, WorksheetFunction.Find(" ", B4, 1 + WorksheetFunction.Find(" ", B4)) - WorksheetFunction.Find(" ", B4) - 1)
        
            last_name = Right(A1, Len(A1) - WorksheetFunction.Find("*", WorksheetFunction.Substitute(A1, " ", "*", Len(A1) - Len(WorksheetFunction.Substitute(A1, " ", "")))))
        End If
        
        Range("C1").Value = last_name & " " & first_name & " " & middle_name
    End Sub

  4. #4
    Forum Expert martindwilson's Avatar
    Join Date
    06-23-2007
    Location
    London,England
    MS-Off Ver
    office 97 ,2007
    Posts
    19,320

    Re: rearrange first last and middle name in a cell

    try instring which is instr instead
    http://www.techonthenet.com/excel/formulas/instr.php
    "Unless otherwise stated all my comments are directed at OP"

    Mojito connoisseur and now happily retired
    where does code go ?
    look here
    how to insert code

    how to enter array formula

    why use -- in sumproduct
    recommended reading
    wiki Mojito

    how to say no convincingly

    most important thing you need
    Martin Wilson: SPV
    and RSMBC

  5. #5
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    The change to instr now gives me a "type mismatch" error highlighting this line:

    middle_name = Mid(B4, InStr(" ", B4) + 1, InStr(" ", B4, 1 + InStr(" ", B4)) - InStr(" ", B4) - 1)
    with this code:

    Sub Inspect()
        Dim old_str As String
        Dim new_str As String
        Dim first_name As String
        Dim last_name As String
        Dim middle_name As String
        Dim regex As Object
        Dim Rng As Range
        Dim InitialRange As Variant
        Dim CompareRange As Variant
        Dim x As Variant
        Dim y As Variant
        ReDim KeepThese(1 To 10000)
    
        
        pos = InStr(Range("A1"), "AKA")
        
        If pos <> 0 Then
            old_str = Right(Range("A1"), Len(Range("A1")) - pos - 2)
    
            new_str = Left(old_str, Len(old_str) - 1)
        
            Range("A1").Value = Trim(new_str)
            
            Set Rng = Range("A1")
    
            Set regex = CreateObject("VBScript.RegExp")
    
            regex.Global = True
            regex.IgnoreCase = True
            regex.Pattern = "(^\w+\s\w+\s\w+)"
    
            If regex.Test(Range("A1").Value) Then
        
                first_name = Left(B1, InStr(" ", B1) - 1)
            
                middle_name = Mid(B4, InStr(" ", B4) + 1, InStr(" ", B4, 1 + InStr(" ", B4)) - InStr(" ", B4) - 1)
        
                last_name = Right(A1, Len(A1) - InStr("*", WorksheetFunction.Substitute(A1, " ", "*", Len(A1) - Len(WorksheetFunction.Substitute(A1, " ", "")))))
            End If
        
            Range("A1").Value = last_name & " " & first_name & " " & middle_name
        
        End If
        
        Set InitialRange = Range("A:A")
        Set CompareRange = Range("B:B")
    
        For Each x In InitialRange
            For Each y In CompareRange
                If x = y Then
                  KeepThese = IIf(Len(x) > Len(y), x, y)
                End If
            Next y
        Next x
    
        For Each Key In KeepThese
            Range("C1").Value = Key
        Next Key
    End Sub
    Note that now I am just targeting A1, for example, but obviously I will need to change that to A1 & i because I would be iterating the length of the column. I just do this now so it makes it easier to troubleshoot.

    Basically, in cell A1 I have something like this:

    In property of AKA Jen S Stephen,
    In cell B1, I have something like this:

    Stephen Jen
    So my VBA above intends to change A1 to this: Stephen Jen S and then which ever is greater length (e.g. Stephen Jen S or Stephen Jen) output it to cell C1.

    Thanks for response.

  6. #6
    Forum Expert martindwilson's Avatar
    Join Date
    06-23-2007
    Location
    London,England
    MS-Off Ver
    office 97 ,2007
    Posts
    19,320

    Re: rearrange first last and middle name in a cell

    i don't know enough vba and i think ill get someone else to have a look in at this but i don't think that's the right construct.

  7. #7
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    O365
    Posts
    20,440

    Re: rearrange first last and middle name in a cell

    Try this

    Sub X()
    
        Dim strOldName As String
        Dim strNewName As String
        Dim lngPos As Long
        Dim vntNames As Variant
        Const AKA = " AKA "
        
        strOldName = Range("A1")
        lngPos = InStr(1, strOldName, AKA, vbTextCompare)
        If lngPos > 0 Then
            strOldName = Trim(Mid(strOldName, lngPos + Len(AKA)))
            If Right(strOldName, 1) = "," Then
                strOldName = Trim(Left(strOldName, Len(strOldName) - 1))
            End If
            vntNames = Split(strOldName, " ")
            strNewName = vntNames(UBound(vntNames))
            vntNames(UBound(vntNames)) = ""
            Range("C1") = strNewName & " " & Trim(Join(vntNames, " "))
        End If
    End Sub
    Cheers
    Andy
    www.andypope.info

  8. #8
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: rearrange first last and middle name in a cell

    Or possibly this
    Sub test()
        Dim FirstNames As String
        Dim n As Long
        Dim arrNames As Variant
        Dim ConstantFound As Boolean
        Const AKA = " AKA "
    
        arrNames = Split(WorksheetFunction.Substitute(Range("A1"), ",", ""))
        For n = LBound(arrNames) To UBound(arrNames) - 1
            If ConstantFound Then FirstNames = FirstNames & " " & arrNames(n)
            If UCase(arrNames(n)) = Trim(AKA) Then ConstantFound = True
        Next
        If ConstantFound Then Range("C1") = arrNames(UBound(arrNames)) & FirstNames
    
    End Sub
    If you need any more information, please feel free to ask.

    However,If this takes care of your needs, please select Thread Tools from menu above and set this topic to SOLVED. It helps everybody! ....

    Also
    اس کی مدد کرتا ہے اگر
    شکریہ کہنے کے لئے سٹار کلک کریں
    If you are satisfied by any members response to your problem please consider using the small Star icon bottom left of their post to show your appreciation.

  9. #9
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Post Re: rearrange first last and middle name in a cell

    if in A1: "IN RIGHT OF AKA PAUL A HERMAN"

    sub snb()
      [B1]=split(split([A1],"AKA ")(1))(2) & space & split(split([A1],"AKA ")(1))(0) & space & split(split([A1],"AKA ")(1))(1)
    end sub
    or
    sub snb()
      columns(1).replace ","," "
      [B1]=split(split([A1],"AKA ")(1))(2) & space & split(split([A1],"AKA ")(1))(0) & space & split(split([A1],"AKA ")(1))(1)
    end sub
    or for the whole column
    sub snb()
      columns(1).replace ","," "
      for each cl in columns(1).specialcells(2)
        cl=split(cl,"AKA")(0) & "AKA " & split(split(cl,"AKA ")(1))(2) & space & split(split(cl,"AKA ")(1))(0) & space & split(split(cl,"AKA ")(1))(1)
      next
    end sub
    Last edited by snb; 04-25-2011 at 03:00 PM.



  10. #10
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: rearrange first last and middle name in a cell

    Hi johnmerlino

    Regexp try..
    Sub StringAddressthree()
        Dim RegEx As Object
        SAddress = Range("A1").Text
        Set RegEx = CreateObject("vbscript.regexp")
            With RegEx
                .Global = True
                 .Pattern = "^(\w+\s)+AKA(\s\w+)(\s\w+)(\s\w+),?"
             SAddress = RegEx.Replace(SAddress, "$4$3$2")
             End With
          Range("C1").text=SAddress
           Set RegEx = Nothing
    End Sub
    Last edited by pike; 04-25-2011 at 09:13 PM. Reason: add ,? to pattern
    If the solution helped please donate to RSPCA

    Site worth visiting: Rabbitohs

  11. #11
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    Thanks a lot for all the responses

    @snb, I tried your technique but it threw an error "Argument Not Optional" highlighting "Space".

    @Marcol, Then I tried your technique and it worked for one cell. So I modified it a little so it loops through length of column A:

    Sub test()
    
      Dim lngLastRow As Long
      lngLastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
         Dim FirstNames As String
        Dim n As Long
        Dim arrNames As Variant
        Dim ConstantFound As Boolean
        Const AKA = " AKA "
      Dim i
    
      For i = 1 To lngLastRow
      
        arrNames = Split(WorksheetFunction.Substitute(Range("A" & i), ",", ""))
        For n = LBound(arrNames) To UBound(arrNames) - 1
            If ConstantFound Then FirstNames = FirstNames & " " & arrNames(n)
            If UCase(arrNames(n)) = Trim(AKA) Then ConstantFound = True
        Next
        If ConstantFound Then Range("C" & i) = arrNames(UBound(arrNames)) & FirstNames
      Next i
    
    End Sub
    This above returns something like this:

    IN RIGHT OF AKA PAUL A HERMAN	 HERMAN PAUL	HERMAN PAUL A
    Benna Ann	                                 Benna Ann Mary	Ann PAUL A Benna
    But rather than this:

    HERMAN PAUL A
    Ann PAUL A Benna
    My intention was to pull the name with the longer length when comparing all of Column A and B (so it wouldn't just be comparing B1 and A1 but perhaps B3 and A2) like this:

    HERMAN PAUL A
     Benna Ann Mary
    It may be a minor change that fixes this, but I don't fully understand your code.

    Thanks for response.

  12. #12
    Forum Guru
    Join Date
    03-02-2006
    Location
    Los Angeles, Ca
    MS-Off Ver
    WinXP/MSO2007;Win10/MSO2016
    Posts
    12,626

    Re: rearrange first last and middle name in a cell

    Does this one fall down?
    Option Explicit
    Sub ParseNames()
        Dim AKA_Pos     As Long, _
            ctrl        As Long, _
            LastRow     As Long, _
            TestCell    As Range, _
            NewString   As String, _
            Fragments   As Variant
            
        LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
        For Each TestCell In Range("A1:A" & LastRow)
        
            AKA_Pos = InStr(UCase(TestCell.Value), " AKA ") + 5
            
            Fragments = Split(Mid(TestCell.Value, AKA_Pos), " ")
            
            For ctrl = 0 To UBound(Fragments)
                Fragments(ctrl) = WorksheetFunction.Substitute(Fragments(ctrl), ",", "")
            Next ctrl
            
            NewString = Fragments(UBound(Fragments))
        
            For ctrl = 0 To UBound(Fragments) - 1
                NewString = NewString & " " & Fragments(ctrl)
            Next ctrl
            
            NewString = Trim(NewString)
            Select Case Len(NewString) > Len(Cells(TestCell.Row, "B").Value)
                Case Is = True
                    Cells(TestCell.Row, "C").Value = NewString
                
                Case Is = False
                    Cells(TestCell.Row, "C").Value = Cells(TestCell.Row, "B").Value
            End Select
        Next TestCell
    End Sub
    Ben Van Johnson

  13. #13
    Forum Expert pike's Avatar
    Join Date
    12-11-2005
    Location
    Alstonville, Australia
    MS-Off Ver
    2016
    Posts
    5,330

    Re: rearrange first last and middle name in a cell

    maybe the pattern you need is

    Sub StringAddressthree()
        Dim RegEx As Object
        SAddress = Range("A1").Text
        Set RegEx = CreateObject("vbscript.regexp")
            With RegEx
                .Global = True
                 .Pattern = "^[\w+\s]+AKA(\s\w+)(\s\w+)?(\s\w+),?"
             SAddress = RegEx.Replace(SAddress, "$3$1$2")
             End With
          range("B1").value= SAddress
    Debug.Print SAddress
           Set RegEx = Nothing
    End Sub

  14. #14
    Forum Expert snb's Avatar
    Join Date
    05-09-2010
    Location
    VBA
    MS-Off Ver
    Redhat
    Posts
    5,649

    Re: rearrange first last and middle name in a cell

    This will do:
    sub snb()
      columns(1).replace ","," "
      for each cl in columns(1).specialcells(2)
        cl=split(cl,"AKA")(0) & "AKA " & split(split(cl,"AKA ")(1))(2) & " " & split(split(cl,"AKA ")(1))(0) & " " & split(split(cl,"AKA ")(1))(1)
      next
    end sub

  15. #15
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: rearrange first last and middle name in a cell

    You were nearly there.

    If you are to use the code I offered to cover a range, you must clear the variable "FirstNames" and reset "ConstantFound" to false before you loop again.
    Sub test()
        Dim FirstNames As String
        Dim lngLastRow As Long
        Dim n As Long, i As Long
        Dim arrNames As Variant
        Dim ConstantFound As Boolean
        Const AKA = "AKA"
        
        lngLastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
        For i = 1 To lngLastRow
            arrNames = Split(WorksheetFunction.Substitute(Range("A" & i), ",", ""))
            For n = LBound(arrNames) To UBound(arrNames) - 1
                If ConstantFound Then FirstNames = FirstNames & " " & arrNames(n)
                If UCase(arrNames(n)) = AKA Then ConstantFound = True
            Next
            If ConstantFound Then Range("C" & i) = Trim(UCase(arrNames(UBound(arrNames)) & FirstNames))
            FirstNames = ""
            ConstantFound = False
        Next i
    
    End Sub

    Alternatively you could change the Sub to a Function and use it as an UDF
    Function ExtractName(rng As Range, Optional strStart As String = "AKA") As String
        Dim FirstNames As String
        Dim n As Long
        Dim arrNames As Variant
        Dim ConstantFound As Boolean
    
        arrNames = Split(WorksheetFunction.Substitute(rng, ",", ""))
        For n = LBound(arrNames) To UBound(arrNames) - 1
            If ConstantFound Then FirstNames = FirstNames & " " & arrNames(n)
            If UCase(arrNames(n)) = strStart Then ConstantFound = True
        Next
        If ConstantFound Then
            ExtractName = Trim(UCase(arrNames(UBound(arrNames)) & FirstNames))
        Else
            ExtractName = ""
        End If
    End Function
    Then in C1
    =ExtractName(A1)
    Drag/Fill Down

    to use a different criteria then, e.g.
    =ExtractName(A1,"OF")
    The UDF might have an advantage in so much as you can correct errors in your source data and the extracted data will automatically update.

    Have a look at the attached demo workbook.

    Hope this helps.
    Attached Files Attached Files

  16. #16
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    Thanks for the responses.

    This one came close:

    Option Explicit
    Sub ParseNames()
        Dim AKA_Pos     As Long, _
            ctrl        As Long, _
            LastRow     As Long, _
            TestCell    As Range, _
            NewString   As String, _
            Fragments   As Variant
            
        LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
        For Each TestCell In Range("A1:A" & LastRow)
        
            AKA_Pos = InStr(UCase(TestCell.Value), " AKA ") + 5
            
            Fragments = Split(Mid(TestCell.Value, AKA_Pos), " ")
            
            For ctrl = 0 To UBound(Fragments)
                Fragments(ctrl) = WorksheetFunction.Substitute(Fragments(ctrl), ",", "")
            Next ctrl
            
            NewString = Fragments(UBound(Fragments))
        
            For ctrl = 0 To UBound(Fragments) - 1
                NewString = NewString & " " & Fragments(ctrl)
            Next ctrl
            
            NewString = Trim(NewString)
            Select Case Len(NewString) > Len(Cells(TestCell.Row, "B").Value)
                Case Is = True
                    Cells(TestCell.Row, "C").Value = NewString
                
                Case Is = False
                    Cells(TestCell.Row, "C").Value = Cells(TestCell.Row, "B").Value
            End Select
        Next TestCell
    End Sub
    But the problem is if the name exists in column a but it doesn't exist in column b, then it won't pull it into column c. I want to pull the one with greater length, but if there is only one name, I still want to pull that one too. Also it was setting the output as first middle last, rather than last first middle.
    Last edited by johnmerlino; 04-27-2011 at 07:20 PM.

  17. #17
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    Here's actually a visual example of what I was looking for:

    JENNIFER T TAMASHIRO	    TAMASHIRO,  JENNIFER
    JORGE J GARCIA	            STANIC,  ZORAN
    Jamie Smith	                    In honor of AKA Jamie L Smith
    	
    Based on above example, what I would like in column C:	
    TAMASHIRO JENNIFER T	
    GARCIA JORGE J	
    ZORAN STANIC	
    Smith Jamie L
    Thanks for response.

  18. #18
    Forum Guru (RIP) Marcol's Avatar
    Join Date
    12-23-2009
    Location
    Fife, Scotland
    MS-Off Ver
    Excel '97 & 2003/7
    Posts
    7,216

    Re: rearrange first last and middle name in a cell

    How about posting a workbook with some sample data?

    Up 'til now you have been given 5 or 6 potential solutions, based on 1 line copied from the forum, that would appear to be insufficient.
    What is your last post meant to represent? Two columns of data? Remove duplicates?.......

    A bit more input from you would not go amiss.

  19. #19
    Forum Contributor
    Join Date
    09-19-2010
    Location
    Philadelphia, PA
    MS-Off Ver
    Excel 2007
    Posts
    140

    Re: rearrange first last and middle name in a cell

    Thanks for response. I don't have worksheet right now, but I will try to put fake data. I been trying to do it on my own.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1