vbams-word

How to inverse name and surname in vba?


I have word documents that always come with a list of people like this:

Director: SURNAME Firstname, director of branch

Members : SURNAME Firstname, member of XX

SUNAME Firstname, member of YY

I'd like to switch the Surname and Firstname to have "Firstname SURNAME", as I use those in this order in other parts of the document. I looked it up online and could only find vba codes for excel, not for word. How can I achieve that ?

I've tried using a variation of With . Find with * and \1 \2 but it doesn't work...

Thanks


Solution

  • According to your sample data (without a middle name), this code will do the job;

    Sub Test()
        Dim regExp As Object
        
        Set regExp = CreateObject("VBscript.RegExp")
        
        regExp.Pattern = "(^|Director\s*:|Members\s*:)\s*(\w+?)\s*(\w+?),"
        regExp.Global = True
        regExp.MultiLine = True
        
        ActiveDocument.Range.Text = regExp.Replace(ActiveDocument.Range.Text, "$1 $3 $2,")
        
        Set regExp = Nothing
    End Sub