Search code examples
vbams-officems-wordvisual-studio-macros

VBA clear formatting from selected paragraph


Having a lot of trouble with this macro:

 ActiveDocument.CopyStylesFromTemplate NormalTemplate.FullName
    With Selection
        .Style = ActiveDocument.Styles("Normal")
        .Range.HighlightColorIndex = 0
        .Font.Shading.Texture = wdTextureNone
        .Font.Name = ActiveDocument.Styles("Normal").Font.Name
        .Font.Size = ActiveDocument.Styles("Normal").Font.Size
    End With

It works perfectly with a line like: This text should be formatted without bold or italics.

And converts it to" This text should be formatted without bold or italics.

However, it only works if I select up to right before the last character and run it. When I double click the line or select the entire line manually and run the macro it seems to have no effect at all.

Any ideas what might be causing this or if there is a different method I should use to remove bold/italicized text within a selection and convert all of the text to Normal style/font?

Edit: This may have to do with running the macro from a keyboard shortcut as it works fine when run manually via the macro menu.


Solution

  • If you want to clear all formatting, I'd suggest this:

    With Selection
        .ClearFormatting
    End With
    

    This resets the paragraph style to Normal and resets all fonts and attributes (that I've tried to set). Note that it resets the paragraph style for the paragraph that includes the selection (so if you've only selected a single word in the paragraph, it still resets the style for the paragraph).

    ref: MSDN: Selection.ClearFormatting

    I didn't see any difference when I added ActiveDocument.CopyStylesFromTemplate NormalTemplate.FullName but I expect this would depend on the complexities of your documents.