REPLACING IN WORD

  • Thread starter Thread starter bertiep
  • Start date Start date
B

bertiep

in MsWord, how do i replace the word left for the word right and word right
for the word left in the same document in the same pass?
 
in MsWord, how do i replace the word left for the word right and word right
for the word left in the same document in the same pass?

It's impossible to do it in one pass; in fact, it takes three passes to do it
properly. Replace

left --> %left%
right --> left
%left% --> right

If you leave out the step of temporarily replacing one of the pair with a third
value (for which I've shown using % signs, so it won't be confused with anything
else), you'll wind up with all of the occurrences saying the same thing.

This is a general principle: when you want to swap two values, you must go
through a temporary value for one of them.
 
I can't swear to it, but I don't think it could be done with the traditional
UI Find and Replace function (not in one pass that is). Word would want to
find all "left" and replace with "right" then all the words would be "right"
and Word would change them all to "left." You would need to Change all the
"left" to some unique sequence then change all the right to some differenct
unique sequece then change the first sequence to "right" and the second to
"left" You might use a macro like this:

Sub ScratchMacro()
Dim oRng As Word.Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = "left"
.Replacement.Text = "*#*"
.Execute Replace:=wdReplaceAll
.Text = "right"
.Replacement.Text = "#*#"
.Execute Replace:=wdReplaceAll
.Text = "*#*"
.Replacement.Text = "right"
.Execute Replace:=wdReplaceAll
.Text = "#*#"
.Replacement.Text = "left"
.Execute Replace:=wdReplaceAll
End With
End Sub


Another way would be to process each word one at a time:

Sub ScratchMacroII()
Dim oWord As Range
Dim i As Long
Dim bUnTrim As Boolean
For i = 1 To ActiveDocument.Words.Count
If ActiveDocument.Words(i).Characters.Last = " " Then bUnTrim = True
Select Case Trim(ActiveDocument.Words(i))
Case Is = "right"
If bUnTrim Then
ActiveDocument.Words(i) = "left" & " "
Else
ActiveDocument.Words(i) = "left"
End If
Case Is = "Right"
If bUnTrim Then
ActiveDocument.Words(i) = "Left" & " "
Else
ActiveDocument.Words(i) = "Left"
End If
Case Is = "left"
If bUnTrim Then
ActiveDocument.Words(i) = "right" & " "
Else
ActiveDocument.Words(i) = "right"
End If
Case Is = "Left"
If bUnTrim Then
ActiveDocument.Words(i) = "Right" &
ActiveDocument.Words(i).Characters.Last
Else
ActiveDocument.Words(i) = "Right"
End If
End Select
bUnTrim = False
Next i
End Sub
 
Back
Top