PDA

View Full Version : Insertbreak - Range vs. Selection



NoSel
05-11-2011, 09:56 PM
This first code snippet works as desired. It takes each InlineShape in a HTML file and replaces it with a page brake. (This is a very small piece of a much larger macro )


For Each Shape In ActiveDocument.InlineShapes
Set Rng = Shape.Range
With Rng
FollowingStyle = .Style
.Delete
.Select
If Left(FollowingStyle, 4) = "Head" Then
Selection.Style = ActiveDocument.Styles("Normal")
Selection.InsertBreak wdPageBreak
Selection.Style = FollowingStyle
Else
Selection.InsertBreak wdPageBreak
End If
End With
Next


Unfortunately, selection objects cause the screen to move despite my attemps to turn off screen updating. Thats a problem for another time though. So to fix the above code I did the following.


For Each Shape In ActiveDocument.InlineShapes
Set Rng = Shape.Range
With Rng
FollowingStyle = .Style
.Delete
.Collapse
If Left(FollowingStyle, 4) = "Head" Then
.Style = ActiveDocument.Styles("Normal")
.InsertBreak wdPageBreak
.Style = FollowingStyle
Else
.InsertBreak wdPageBreak
End If
End With
Next


This version runs to completion, but when I run a test document, the table format is completely messed up and I end up with 275 page document instead of a 182 page document (all due to misformatted tables). Side note: the table formating isn't done until later on in the macro. Inserting page breaks is one of the first things performed. What is interesting to me, is that if I stop the macro right after the page breaks are inserted and compare the two documents ( one from each version above ) I can't see a difference between the formating.

I'm pretty sure I've read something from microsoft about the three ways to insert text and each require selecting the text. I just don't know why the verison using only range objects fails or if I can even do the above using only range objects.

Thanks for the help,
John

Frosty
05-12-2011, 06:43 PM
It's tough to know exactly, at the moment... but a couple thoughts:

1. inserting text from a macro does not require the use of the selection object.

2. using a for each loop when you are deleting objects from the collection is going to cause you problems. In this case, I would make a guess that it isn't causing you problems when you .Select because that would trigger a "recount" of the collection. Better to use the following structure:

For i = ActiveDocument.InlineShapes.Count To 1 Step - 1
Set rng = ActiveDocument.InlineShapes(i).Range
Next