0

There's this nice functionality in MS Word that gets rid of leading and trailing spaces in the entire document whenever you select the whole text and center it, then go back to desired alignment.

So this (space)(space)(space)text text text(space)(space) should result with this text text text

It has repeatedly worked for me when I do it manually by clicking on the center icon on quick access toolbar or ribbon in Word. But whenever I use the code below to manage the same automatically via macro, this solution doesn't work for me. Those undesired spaces are still there.

Selection.WholeStory
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter 'after this, there should be no leading/trailing spaces anymore
Selection.ParagraphFormat.Alignment = wdAlignParagraphJustify

Have you experienced this before? Can you replicate such result?

Rayearth
  • 345
  • 3
  • 5
  • 13
  • 1
    Probably you should use the search/replace command for this. First, replace two spaces with one space. Then, to replace leading spaces, search for `^p[space]` and replace with `^p`, and for trailing spaces search for `[space]^p` and replace with `^p`. `^p` is the paragraph character and might be replaced with `^l` for newline instead. `[space]` needs to be replaced in Word by a normal blank space (won't show in the markup on superuser). I'm not into macros, but I do this often manually. I'm sure it's quite easy to write a macro for this – 1NN Apr 26 '21 at 09:13
  • I also found that ParagraphFormat.Alignment does not work in a macro. – harrymc Apr 26 '21 at 09:37
  • Well, such macro will work, but not for the leading space of the very first line as there is no `^p` before that. But thanks for the suggestion of a workaround. – Rayearth Apr 26 '21 at 11:29

1 Answers1

1

Check if this macro works for you. One negative consequence of it is if you wanted two spaces between sentences it would eliminate them. However, if your documents normally use only one space between sentences, then the macro should work fine for you.

Sub elimBlankSpaces()
    Dim rng As Word.Range
    Set rng = ActiveDocument.Content
    With rng.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = " {2,}" 'look for 2 or more
        .Replacement.Text = "" 'replace with none
        .Forward = True
        .Wrap = Word.WdFindWrap.wdFindStop
        .Format = False
        .MatchWildcards = True
    End With
    rng.Find.Execute Replace:=Word.WdReplace.wdReplaceAll
    rng.Find.ClearFormatting
    rng.Find.Replacement.ClearFormatting
End Sub
Rich Michaels
  • 2,841
  • 2
  • 11
  • 20