View Single Post
 
Old 08-05-2023, 12:27 AM
East East is offline Windows 10 Office 2021
Novice
 
Join Date: Aug 2023
Posts: 7
East is on a distinguished road
Default After first replacement, other search results are incorrectly selected

Hello

With the help of some AI bots, the Word macro below was generated to use regex in Find and Replace with a YesNoCancel prompt (macro runs from cursor position). The problem with this macro is that when the Find string and Replace string are not of the same length, the first replacing is done correctly, but then the other search results are incorrectly selected, and no replacing is showing. AI bots are suggesting updating cursor position, but all their solutions don't work!

Any help is much appreciated.

PS: The pattern and replacementtext in the macro below are just examples. I need the macro for cases that are not supported by wildcards.

Here's the macro:

Code:
Sub PromptRegExReplace()
    Dim regEx As Object
    Dim match As Object
    Dim matches As Object
    Dim rng As Range
    Dim response As Integer
    Dim replacementText As String

    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Pattern = "([0-9])"
    regEx.Global = True

    ' Get the current cursor position
    Dim cursorPosition As Long
    cursorPosition = Selection.Start

    ' Set the range to start from the cursor position until the end of the document
    Set matches = regEx.Execute(ActiveDocument.Range(cursorPosition, ActiveDocument.Range.End).text)
    replacementText = "$1abc"

    For Each match In matches
        Set rng = ActiveDocument.Range(match.FirstIndex + cursorPosition, match.FirstIndex + match.Length + cursorPosition)
        rng.Select
        response = MsgBox("Replace this instance?", vbYesNoCancel)
        If response = vbYes Then
            Application.ScreenUpdating = False
            rng.text = regEx.replace(rng.text, replacementText)
            Application.ScreenUpdating = True

        ElseIf response = vbCancel Then
            Exit Sub
        End If
    Next match

End Sub
Reply With Quote