I'm getting a runtime error 91 on the following Word VBA:
Dim myStoryRange As Object
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.find
.Text = "test to search"
.Replacement.Text = "text to replace"
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute replace:=wdReplaceAll
End With
Next myStoryRange
The error occurs inconsistently on about half of the computers that run the macro.
Thoughts?
Per PatricK's suggestion I've changed the code to read:
Dim myStoryRange As Range
For xStories = 1 To ActiveDocument.StoryRanges.Count
Set myStoryRange = ActiveDocument.StoryRanges.Item(xStories)
With myStoryRange.find
.Text = "[Client Name]"
.Replacement.Text = Client
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute replace:=wdReplaceAll
End With
Next xStories
This seems to fix the Error 91. However, I'm still getting an odd result. This code fails at line #5 (with myStoryRange.find) with the error "The Requested Member of the Collection does not exist" on the second item in the collection.
It fails when there IS a member of the collection. In other words, there are 7 xStories, it fails on xStories = 2. And xStories = 2 is a complete item with all of the properties referenced present.
As an FYI, I'm trying to replace a bit of text in the header of the document. I'm getting a failure on a StoryRange item that is in the header, rather than the body of the document. Can that be the problem?
Dim myStoryRange As Range
? You may have to use For loop withActiveDocument.StoryRanges.Count
andSet myStoryRange = ActiveDocument.StoryRanges.Item(#)
– PatricKStoryRanges(wdPrimaryHeaderStory)
instead of looping through all the stories? – xidgel