Range of a field

B

Bear

[Word 2000 on Windows XP]

This is about creating page number prefixes of the form C.9, where C is the
SEQ nubmer of the chapter. I can do it all manually through the UI, but I'm
trying to do it programatically.

I can iterate through the fields collection in each header and footer and
find any PAGE fields, BUT I can't figure out how to establish a range object
that lets me insert stuff just before this field.

objRange = objField.Result just doesn't work reliably -- things get
inserted in the middle of the field code, when they get inserted at all. It
works when you use selections in the active document, but not when you use
range objects.

Any clues?

Bear
 
C

Chuck Henrich

Have you tried getting around the problem with a selection range? It may not
be the best solution but it works...

'set range to your range - Selection.Range here is for
'example only
Set rngRange = Selection.Range

Set fldField = ActiveDocument.Fields.Add( _
Range:=rngRange, _
Type:=wdFieldPage, _
PreserveFormatting:=True)

fldField.Select

Selection.Range.InsertBefore "Hello world"
 
B

Bear

Chuck:

Thanks for the suggestion. What you suggest does work -- that's what's been
frustruating me. It works fine for selections, but not for ranges. Maybe it's
because Word can't properly correlate a field result within a range object.

Using the "selection" approach I could stop screen updating, rip through all
the headers and footers updating my fields, then restor the original
selection. I just hate to have to resort to that.

The only workaround I've found so far is to set a range to the field result,
then unlink the field. That seems to drop the range into the realm of normal
range behavior. From that point on I can reinsert the field I just unlinked
and I'm now in a position to use the range as I would use a selection.

Clunky too, but maybe that's the best I can do. Here's the pertinent code:

Set objRange = objField.Result
objField.Unlink
objRange.Fields.Add _
Range:=objRange, _
Type:=wdFieldPage, _
PreserveFormatting:=False
objRange.InsertAfter "."
objRange.Collapse
objRange.Fields.Add _
Range:=objRange, _
Type:=wdFieldSequence, _
Text:="Chapter \c", _
PreserveFormatting:=False


Bear
 
D

Doug Robbins

You can do it this way:

Dim myrange As Range
Dim afield As Field
For Each afield In
ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Fields
If afield.Type = wdFieldPage Then
Set myrange = afield.Code
myrange.Start = myrange.Start - 1
myrange.Collapse wdCollapseStart
myrange.InsertBefore "C-"
End If
Next


--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 

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