A family of Microsoft word processing software products for creating web, email, and print documents.
Replace the recorded Selection.Find operations with searches on a duplicated Range and set Wrap:=wdFindStop, which confines both replacements to the originally selected text.
Sub HandSpcFix()
Dim scope As Range
If Selection.Type = wdSelectionIP Then
MsgBox "Select the text to process first."
Exit Sub
End If
Set scope = Selection.Range
ReplaceInRange scope.Duplicate, " ", ""
ReplaceInRange scope.Duplicate, "^p", " "
End Sub
Private Sub ReplaceInRange(ByVal target As Range, _
ByVal findText As String, _
ByVal replaceText As String)
With target.Find
.ClearFormatting
.Replacement.ClearFormatting
.Execute FindText:=findText, ReplaceWith:=replaceText, _
Forward:=True, Wrap:=wdFindStop, _
Format:=False, Replace:=wdReplaceAll
End With
End Sub
A Word Range represents a specific contiguous part of the document and can be manipulated independently of the visible selection.^1^ Range.Duplicate creates another range with the same boundaries, allowing each Find/Replace pass to operate on that scope without moving the user's selection.^2^
The significant setting in the recorded macro is:
.Wrap = wdFindAsk
wdFindAsk tells Word to display a prompt after searching the selection or range and offer to search the rest of the document. wdFindStop ends the search at the boundary instead.^3^ Using Range.Find also avoids the way Selection.Find changes the active selection when it finds text.^4^
Select only the four lines to transform, then run HandSpcFix. The result should be:
♠K8 ♥54 ♦KQ10953 ♣KJ10
If the selection includes the final paragraph mark after ♣ K J 10, that mark will also be replaced and may join the result to the following paragraph. Exclude that final paragraph mark when selecting unless that join is intended.
References