Ranges and .Characters.Count

O

OughtFour

I wrote this routine to insert a paragraph before every section break in
document vDoc:

For Each vSec In vDoc.Content.Sections
With vSec
If .Index > 1 Then
'Operate on all but the first section
'(since there are always 1 more section than breaks)
'insert para
' ******>>>>>>>>error on next line
vDoc.Content.Characters(.Range.Start).InsertBefore Chr(13)
End If
End With
Next vSec

It works fine on a simple test document, but when I tried it on a large file
it gave me an error on the last section of the document (5941, the requested
member of the collection does not exist).

Some poking and prodding disclosed that the value of
vDoc.Content.Characters.Count
is less than
vSec.Range.Start
when vSec is the last section in the document.

(although vDoc.Content.End is greater than either).

This has shown me exactly enough to see that I am over my head.

Why the difference between .Content.Characters.Count and Content.End?

How do you say, "Insert x before the start of range y?"

What am I doing wrong?

Gratitude for any help at all!
 
M

Marty

Howdy,

The following code might be useful. It depends on the observation that the section break is treated as the last character in the range that encompasses the section.

'*****************
'* CODE BEGINS *
'*****************
Dim _
secNext As Section

For Each secNext In ActiveDocument.Sections
If secNext.Index > 1 Then
secNext.Range.Characters.Last.InsertBefore vbCr
End If
Next secNext
'*****************
'* CODE ENDS *
'*****************

Marty
 
O

OughtFour

Marty said:
Howdy,

The following code might be useful. It depends on the observation that
the section break is treated as the last character in the range that
encompasses the section.

'*****************
'* CODE BEGINS *
'*****************
Dim _
secNext As Section

For Each secNext In ActiveDocument.Sections
If secNext.Index > 1 Then
secNext.Range.Characters.Last.InsertBefore vbCr
End If
Next secNext
'*****************
'* CODE ENDS *
'*****************

Marty

Thank you, Marty. That should solve my problem.

I confess I still yearn to understand why .Content.Characters.Count is
sometimes not equal to .Content.End--and just what was wrong about my
original approach--but your illustration of what works is arguably the
better half of the deal.

Thanks again!
 

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