View Single Post
 
Old 12-24-2023, 04:31 AM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2019
Expert
 
Join Date: Aug 2014
Posts: 4,106
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

A solution to your request depends on several issues which are not known. The first part is simple enough, provided the names are all of similat construction as you described. The second part assumes that there would only be one comma in the paragraph and that is directly after the name you want to find. If there are additional commas the code below will not work.
The code writes to two strings, here shown in a text box. If there is no comma in the paragraph, the second string has no content.

Code:
Sub Macro1()
Dim oRng As Range
Dim sName1 As String, sName2 As String
    Set oRng = ActiveDocument.Paragraphs(1).Range
    With oRng
        'get last name of first paragraph
        'If the last character is punctuation
        Do While Len(.Words.Last) = 1
            .End = .End - 1
        Loop
        .Collapse wdCollapseEnd
        .MoveStart wdWord, -3
        'correct for middle initial
        If Len(.Words(1)) = 1 Then .MoveStart wdWord, -1
        sName1 = oRng.Text
        
        'get last name before comma
        .Start = ActiveDocument.Paragraphs(1).Range.Start
        .End = InStr(1, .Text, Chr(44))
        If .Words.Count > 3 Then
            .End = .End - 1
            .Collapse wdCollapseEnd
            .MoveStart wdWord, -3
             'correct for middle initial
            If InStr(1, .Text, Chr(46)) Then .MoveStart wdWord, -1
            sName2 = oRng.Text
        End If
        MsgBox sName1 & vbCr & sName2
    End With
    Set oRng = Nothing
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote