View Single Post
 
Old 04-30-2023, 09:09 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,187
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

You can find whitespace (^w) rather than just a single space to do the first replaces in one pass.

Your code was using selection and stopping at the end of the document (.Wrap) and it never moved the selection back to the top for the second pass so the second part could only search down after the last found item from the first replacements.

f you open a With Selection.Find, it doesn't make sense to do an End With and immediately follow it with more Selection.Find commands. I know Microsoft records a macro like this but it is one of my pet hates.

Try this modified code
Code:
Sub ReplaceMe()
   ' Attempt to make every example as one paragraph
    ' This part removes spaces from before a paragraph, up to three spaces
    With ActiveDocument.Range.Find
      .ClearFormatting            'ensures no sticky formatting remains from earlier searches
      .Text = "^w^p"              'finds whitespace (tab or space) followed by a paragraph mark
      .Replacement.Text = "^p"    'replace with just the paragraph mark
      .Forward = True
      .Wrap = wdFindContinue      'wraps back to continue from top if search didn't start there
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      .Execute Replace:=wdReplaceAll
      
    ' Finds paragraphs ending with lowercase letter, comma, colon or semicolon and replaces the paragraph character with a space
    '   This needs to have MatchWildCards = true
    '   because there are wildcards in the Find.Text part
    '   For wildcards, see https://wordmvp.com/FAQs/General/UsingWildcards.htm
      .Text = "([:;,a-z])^13"
      .Replacement.Text = "\1 "
      .MatchWildcards = True
      .Execute Replace:=wdReplaceAll
    End With
End Sub
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote