Reputation: 5779
I have a VBA code in word that iterates through two arrays of strings, finds the text in the document from one array, and replaces it with the corresponding string in the other array like so:
with application.activedocument.content.find
for i=1 to 100
.text=array1(i)
.replacement.text=array2(i)
.forward=true
.matchcase=true
.wrap=wdFindContinue
.matchwholeword=true
.matchwildcards=false
.matchallwordforms=false
.matchprefix=true
.matchsuffic=true
.matchsoundslike=false
.execute replace:=wdReplaceAll
next
end with
This replaces all the cases indiscriminately. Is there a way to include an if clause that makes it so it won't replace a word if it is the first word in a line? I'm not sure what the vba code for testing if something is the first word of a line.
Any help would be appreciated.
Upvotes: 0
Views: 741
Reputation: 851
As there isn't a conditional in the Find and Replace to not replace words at the start of a line, there are 2 options that I can think of:
Neither of these are particularly elegant, but I went with the second option. I generally prefer to use a Range object rather than using Selection, but in this instance the Selection seemed easier to work with. Note that you'll need to turn off the wrap for this to work.
For i = 1 To 100
Selection.MoveStart WdUnits.wdStory, Count:=-1
Do
Selection.MoveRight unit:=wdWord, Count:=1
Selection.EndKey unit:=wdLine, Extend:=wdExtend
With Selection.Find
.Text = array1(i)
.Replacement.Text = array2(i)
.Forward = True
.MatchCase = True
.MatchWholeWord = True
.MatchWildcards = False
.MatchAllWordForms = False
.MatchPrefix = True
.MatchSuffix = True
.MatchSoundsLike = False
.Execute Replace:=wdReplaceAll
End With
Selection.MoveStart unit:=wdLine, Count:=1
Loop Until Selection.End = ActiveDocument.Range.End
Next
Upvotes: 1