Me92771
Me92771

Reputation: 13

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

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:

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

Upvotes: 1

Views: 50

Answers (1)

Timothy Rylatt
Timothy Rylatt

Reputation: 7850

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

Upvotes: 2

Related Questions