Home > Software engineering >  Word VBA: Delete specific text in headings
Word VBA: Delete specific text in headings

Time:06-10

I have a document containing tags, and now I would like to delete all the tags in headings only. Please refer to the example below. The tags also appear in the content as well, but I only need to delete the tags in Heading1, Heading2, Heading3.

e.g.

(before)

1 Hello world[A]

1.1 Hello Tokyo[A][B]

1.1.1 Hello NYC[C]

blablablabla[A][B]

(after)

1 Hello world

1.1 Hello Tokyo

1.1.1 Hello NYC

blablablabla[A][B]

The following is my code to work, but the result shows the tags in the content are deleted too. Take the above as example, [A]and[B] in blablablabla[A][B] are also deleted with my code. Please help me find out is there anything wrong in my code, thanks!

Sub mainsub()
  DeleteBrackets wdStyleHeading1
  DeleteBrackets wdStyleHeading2
  DeleteBrackets wdStyleHeading3
'I have other code in my main sub, just show my way to call the functioin
End Sub

Public Sub DeleteBrackets(headingStyle As WdBuiltinStyle)
    Application.ScreenUpdating = False
    Selection.HomeKey Unit:=wdStory
        With Selection.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Style = headingStyle
            .Text = "\[*\]"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchByte = False
            .MatchAllWordForms = False
            .MatchSoundsLike = False
            .MatchWildcards = True
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
        
End Sub

CodePudding user response:

Change

.Format = False

to

.Format = True

  • Related