Word VBA Macro that inserts spaces before and after italicized text surrounded by regular text

Viewed 35

I tried to create a macro that inserts an empty space before and after italic text if it is surrounded by normal characters, like so:

  • What it is supposed to look like: word1 word2 word3
  • What it actually looks like: word1word2word3

So far, the best I could come up with only replaces the italicized text however.

With Selection.Find
 .ClearFormatting
 .Text = ""
 .Replacement.ClearFormatting
 .Replacement.Text = " "
 .Font.Italic = True
 .MatchWholeWord = False
 While .Execute
  .Execute Replace:=wdReplaceAll, Forward:=True, _
 Wrap:=wdFindContinue
Wend
End With
End Sub

How should I approach solving this issue? Thank you in advance

1 Answers

You don't need a macro to do this. Find and Replace will do it for you.

Press Ctrl+H to display the Advanced find dialog.

With your cursor in the "Find what" box click on Format and then choose Font and Italic.

Move your cursor to the "Replace with" box click on Special and select "Find What Text" from the options menu. Add your spaces as required. Your dialog should now look like this:

enter image description here

Click Replace All and you're done.

If you really must use code:

Sub AddSpaceToItalicText()
    With ActiveDocument.Content.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Font.Italic = True
        .Text = ""
        .Replacement.Text = " ^& "
        .Forward = True
        .Wrap = wdStop
        .Format = True
        .Execute Replace:=wdReplaceAll
    End With
End Sub
Related