Using ActiveDocument.GoTo in a loop

C

ckxplus

I've got a document with 3 table of contents levels and I want to
reduce this to 1 level. I know that the table of contents is defined
byTC fields in 3 consecutive paragraphs. So I want to replace the TC
field in the first paragraph by the new text, delete the TC fields in
the next 2 paragraphs, then move on to the next TC field.

It's the last part I can't figure out. I can get the contents of the
first TC field using:

Dim aRange As Range
Set aRange = ActiveDocument.GoTo(what:=wdGoToField,
Which:=wdGoToFirst, Name:="TC")

I can then make the modifications, but how would I move on to the next
TC field? I can use:

Set aRange = ActiveDocument.GoTo(what:=wdGoToField, Which:=wdGoToNext,
Name:="TC")

But how can I test if the GoTo was successful? Is there a property of
aRange I can use to loop through all the TC fields of the document
until all have been modified or deleted?

Because I'm going to delete fields, I can't use the "for each fld in
activedocument.fields" approach. Any other suggestions?

Advance thanks for any help,
John Hendrickx
 
R

Russ

There is a tableofcontents collection and fields collection. You can iterate
through them both with a 'for each' statement. To test for certain field
types, use the object browser in Word VBA Editor and search for wdfieldtype
in order to get a list of field types and use an if statement to act on only
certain types of fields.

For each aField in ActiveDocument.Fields
If aField.Type = ... then
 
R

Russ

John,
If you did want to do it backwards because deleting *may* cause problems you
could use:
Dim lngCount As Long
For lngCount = ActiveDocument.Fields.Count To 1 Step -1
If aField(lngCount).Type = ... Then
...
Next lngCount

But a For Each loop is usually faster than a counter loop.
Keep in mind, also, that we are not looping through all the storyranges for
fields.
 
R

Russ

Oops, I left the aField from copy and paste. See below.
John,
If you did want to do it backwards because deleting *may* cause problems you
could use:
Dim lngCount As Long
For lngCount = ActiveDocument.Fields.Count To 1 Step -1
If aField(lngCount).Type = ... Then
If ActiveDocument.Fields(lngCount).Type = ... Then
 

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