StoryRanges not working

C

Clive Tolley

Could someone please tell me why the following code works (i.e. goes through
the various Stories) ...

For Each aStory In ActiveDocument.StoryRanges
Selection.HomeKey Unit:=wdStory, Extend:=wdMove

With aStory.Find
.Text = "text"
.Replacement.Text = "XXXXXXXX"
.Execute Replace:=wdReplaceAll
End With

Next aStory

.... but the following does not (and it makes no difference whether Range or
Selection is used, or what character the Range/selection is moved to):

Dim aStory As Word.Range
Dim aRange As Word.Range
Dim strA As String
Dim i As Integer

Selection.HomeKey Unit:=wdStory, Extend:=wdMove
Set aRange = ActiveDocument.Range(Start:=0, End:=0)

For Each aStory In ActiveDocument.StoryRanges
For i = 1 To aStory.Paragraphs.Count
With aRange
.MoveUntil Cset:=Chr$(13)
.MoveStart Unit:=wdCharacter, Count:=-1
.Select
End With
strA = aRange.Text
Do While Asc(strA) = 32
aRange.Collapse Direction:=wdCollapseStart
aRange.Delete Unit:=wdCharacter, Count:=1
aRange.MoveStart Unit:=wdCharacter, Count:=-1
strA = aRange.Text
Loop
With aRange
.MoveUntil Cset:=Chr$(13)
.MoveStart Unit:=wdCharacter, Count:=1
End With
Next i
Next aStory

Thanks
 
C

Clive Tolley

Thanks, I'll try what you suggest there. I know the Selection doesn't need to
be there - it is left over from previous version, and as you see I'm trying
to use Range, but haven't refined it all yet. The second piece is supposed to
remove spaces before ends of paragraphs, including (in particular) ends of
footnotes, where the end of footnote 'paragraph' mark seems to be impervious
to coding (hence the aim of selecting (or ranging) the previous character
and deleting it if it is a space. I dare say it's not elegant etc. - I'm not
that experienced. But in particular I want to ensure that moving through all
Stories is going to work, and this code won't move outside the main story at
all, which is baffling me.
 
C

Clive Tolley

Ah, now I see what I have done - very silly! I forgot to redefine the Range
as within the Story instead of the ActiveDocument. Now it works, with the
proper loop structure recommended previously.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top