Add Method for the Fields Collection Issue

K

kdh

In an attempt to automate the conversion of document headers, I have been
stumped by the Add method of the Fields collection continually overwriting
the first field rather than adding additional fields.

ActiveDocument.Fields.Add _
Range:=ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range, _
Type:=wdFieldDocProperty

Trying to add multiple fields just continually modifies Item 1 inside the
Fields collection. I can manipulate the one field it does create as desired
and I can manipulate multiple fields if they are first created manually in
Word first. I just can't seem to get more than one field created at any given
time. Any suggestions would be appreciated.
 
J

Jay Freedman

Without seeing your whole macro, I'll guess that the problem is the
Range parameter you're passing to the Add method. If you call the same
statement repeatedly, the Range for the second call is the whole
header, which includes the field inserted by the first call, and so
on.

Instead, declare a Range object and "move" it along the header,
collapsing it at the end each time before adding the next text or
field:

Sub demo()
Dim oRg As Range
Dim oFld As Field

' first field
Set oRg = ActiveDocument.Sections(1).Headers( _
wdHeaderFooterPrimary).Range
oRg.Collapse wdCollapseEnd

Set oFld = ActiveDocument.Fields.Add( _
Range:=oRg, Type:=wdFieldEmpty)
oFld.Code.Text = "DocProperty Author"
oFld.Update

' second field
Set oRg = ActiveDocument.Sections(1).Headers( _
wdHeaderFooterPrimary).Range
With oRg
.Collapse wdCollapseEnd
.Text = vbTab
.Collapse wdCollapseEnd
End With

Set oFld = ActiveDocument.Fields.Add( _
Range:=oRg, Type:=wdFieldEmpty)
oFld.Code.Text = "Date \@yyyy-MM-dd"
oFld.Update

' third field
Set oRg = ActiveDocument.Sections(1).Headers( _
wdHeaderFooterPrimary).Range
With oRg
.Collapse wdCollapseEnd
.Text = vbTab
.Collapse wdCollapseEnd
End With

Set oFld = ActiveDocument.Fields.Add( _
Range:=oRg, Type:=wdFieldPage)
End Sub
 

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