Share via

Finding the wrong one.

SteveD 555 Reputation points
2025-11-28T22:59:52.2866667+00:00

Hello from Steve

I am asking the below script to find the second occurrence "1 EL VENCEDOR".

At this time it is finding text "11 ELYSIAN".

Can the below script be modified please to find the second occurrence "1 EL VENCEDOR".

With Selection.Find

    .Text = "[0-9]{1,} [A-Z]{1,}"

    .Replacement.Text = ""

    .Forward = True

    .Wrap = wdFindStop

    .Format = True

    .MatchCase = True

    .MatchWholeWord = True

    .MatchAllWordForms = False

    .MatchSoundsLike = False

    .MatchWildcards = True

End With

Selection.Find.Execute

Selection.Fields.Update

strText = Selection.Text

Selection.Collapse Direction:=wdCollapseStart

Selection.MoveRight Unit:=wdCharacter, Count:=1

With Selection.Find

    .Forward = False

    .Wrap = wdFindStop

    .MatchCase = True

    .MatchWholeWord = True

    .Text = strText

    .MatchWildcards = True

    .Execute
Microsoft 365 and Office | Word | For home | Windows
0 comments No comments

1 answer

Sort by: Most helpful
  1. AI answer

    2025-11-28T23:00:02.05+00:00

    To modify your script to find the second occurrence of "1 EL VENCEDOR", you can adjust the Selection.Find.Execute method to loop through the occurrences until you reach the second one. Here's a modified version of your script:

    Dim occurrenceCount As Integer
    occurrenceCount = 0
    
    With Selection.Find
        .Text = "1 EL VENCEDOR"
        .MatchCase = True
        .MatchWholeWord = True
        .Wrap = wdFindContinue
        .Execute
    
        ' Loop until the second occurrence is found
        Do While .Found
            occurrenceCount = occurrenceCount + 1
            If occurrenceCount = 2 Then
                Exit Do
            End If
            .Execute
        Loop
    End With
    
    If occurrenceCount = 2 Then
        ' The second occurrence is found
        strText = Selection.Text
        Selection.Collapse Direction:=wdCollapseStart
        Selection.MoveRight Unit:=wdCharacter, Count:=1
    Else
        MsgBox "Second occurrence not found."
    End If
    

    In this script, we count the occurrences of "1 EL VENCEDOR" and exit the loop when the second one is found. If the second occurrence is not found, a message box will notify you.


    References:

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.