简体   繁体   中英

MS Word 2016 Macro Regex Replace

I am trying to code a macro using Regex and my pattern is \\(\\bTopic \\d+\\b\\) and macro should remove (Topic 1) and (Topic 2) from all questions in the whole document, but my macro code is not working. Thanks for your help.

Input:

QUESTION NO: 1 (Topic 1)

QUESTION NO: 15 (Topic 2)

Result should be

QUESTION NO: 1

QUESTION NO: 15

Macro Code

Sub RemoveQuestionTopic()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = "\(\bTopic \d+\b\)"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

The regexp syntax differs from normal regexp. If you replace your expression with this:

.Text = "\(Topic ([0-9]@>)\)"

you will get the expected result. No need to use VBScript.Regexp in this case.

The Find functionality provide only a very limited support to the regular expressions. You need to use VBScript.Regexp as shown below.

Try this Code:

Sub RemoveQuestionTopic()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting

    strReplacementText = "++__++"
    ActiveDocument.Select
    Set objReg = CreateObject("VBScript.Regexp")
    objReg.Pattern = "\s*\(Topic\s*\d+\)"
    objReg.Global = True
    Selection.Text = objReg.Replace(Selection.Text, strReplacementText)

    With Selection.Find
        .MatchWildcards = True
        .Text = strReplacementText
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = True
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

Regex Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM