You may need to give more precise details, but...
Sub CheckOutPrior()
Dim r As Range
Dim Var1 As String
Dim Var2 As String
Var1 = "wn"
Var2 = "yadda"
Set r = ActiveDocument.Range
With r.Find
.ClearFormatting
Do While .Execute(Findtext:=Var1, Forward:=True) = True
r.MoveStart Unit:=wdCharacter, Count:=-1
If Left(r.Text, 1) = "o" Then
r.MoveStart Unit:=wdCharacter, Count:=1
r.Text = Var2
r.Collapse Direction:=wdCollapseEnd
End If
r.Collapse Direction:=wdCollapseEnd
Loop
End With
Set r = Nothing
End Sub
The second
r.Collapse Direction:=wdCollapseEnd
(after the the test of the prior character to see if it is "o" ) is VERY
VERY important. It is not there, this goes into an infinite loop.
So say you have:
The quick brown fox
The quick brawn fox
Notice in one case the prior character is "o", and in the other it is "a".
What the code does:
1. makes a Range object of the document
2. use Find with that range to look for "wn" - but could of course anything
3. moves the start of the found range "wn" (if found) one character to the
left
eg. it finds the "wn" in the first sentence above, anjd makes the range
"own"
4. test the first character - is it "o", or not
5. if it IS "o", then it moves the start BACK one character, in other words,
to the original found text (ie. "wn"), and replaces that with Var2 ("yadda")
6. collapses to the end, and continues on.
7. if it is NOT "o", it collapses to the end, and continues on.
Result?
The quick broyadda fox - "wn" is replaced with "yadda"
The quick brawn fox - nothing
The FIRST "wn" did have "o" as the character just before...so it got changed.
The SECOND "wn" did NOT have "o" as the character before...so the code does
nothing, and goes on to the next "wn".
Hope this helps. This is only one possible way of doing this. You do not
specific - and you should - precisely the logic requirements.
For example: are you looking for whole words? You do not say, just "found
string". If it is whole words, then the prior character will be a space. In
which case, exactly whyare you testing?
If it is not a whole word, then you are looking for characters IN a word. It
seems odd that you would replace some characters within a word. Not that it
is not a real possible requirement, but I am not precisely clear on what you
are trying to do.
Nomey wrote:
>Hi all,
>
>Is there a way to evaluate the character before and after the found string in a routine like this:
>
> With rTmp.Find
> .ClearFormatting
> .Text = var1
> .MatchWholeWord = True
> .MatchWildcards = False
>'evaluate character here?
> .Replacement.ClearFormatting
> .Replacement.Text = var2
> .Execute Replace:=wdReplaceAll
> End With
>
>Something like:
>
> If 'prevous charecter is a tab or a carriage return or ". " Then
> 'use a capital for the first character in the replacement string
> Else 'use no initial capital in the replacement string
> End If
>
>Best regards,
>Shirley
--
Message posted via OfficeKB.com
http://www.officekb.com/Uwe/Forums.aspx/word-programming/200711/1