loop thru Merge Field In Header and Footer

K

kalyan

Hi All

In my template am having merge fields in the header and footer
sections of the document...along with the PAGE field...so excluding
these PAGE field i need to unlink all the other merge fields...can any
body suggest a macro code to perform this action...

Earlier help is highly appreciated!!!!!!!

my code is as follows

Dim oHeader As HeaderFooter
Dim oFooter As HeaderFooter
Dim oSection As Section
Dim a

For Each oSection In ActiveDocument.Sections
For Each oFooter In oSection.Footers
For a = 1 To oFooter.Range.Fields.Count
If oFooter.Range.Fields(a).Code.Text <> "PAGE" Then
oFooter.Range.Fields(a).Unlink
oFooter.Range.Fields(a).Select
Selection.ClearFormatting(using this to unhilight/
deshade the result)
End If
Next
Next
Next
Set oFooter = Nothing
Set oHeader = Nothing
Set oSection = Nothing

but am getting the error collection doesn't exist

Thanks & Regards
Kalyan
 
T

Tony Jollans

Your problem is that, by Unlinking, you are deleting the field, so you
cannot then Select it - the precise error, and place where it happens may
not be the same evry time, and will depend on the exact content of your
document.

To avoid errors of this type, when deleting members of a collection, you
should always work from the end back towards the beginning. So, the first
thing to change is to make your inner loop go like this:

For a = oFooter.Range.Fields.Count To 1 Step -1

This, alone, will not solve your problem in this instance, however, because
you are still trying to select a field after unlinking/deleting it. A quick
fix would be to swap the lines:

oFooter.Range.Fields(a).Unlink
oFooter.Range.Fields(a).Select

.. to give this ..

oFooter.Range.Fields(a).Select
oFooter.Range.Fields(a).Unlink

A better fix would be to not Select at all, and work on the Range.

When you get over this problem, you may have further issues checking for
"PAGE" the way you do. Again, this depends on your document content, but it
would be safer to use:

If Trim(UCase(oFooter.Range.Fields(a).Code.Text)) <> "PAGE" Then
 
L

Lene Fredborg

Instead of the line:
If oFooter.Range.Fields(a).Code.Text <> "PAGE" Then

I would use:
If oFooter.Range.Fields(a).Type <> wdFieldPage Then

In that case, the use of spaces and upper/lowercase in the field code would
not matter.

--
Regards
Lene Fredborg - Microsoft MVP (Word)
DocTools - Denmark
www.thedoctools.com
Document automation - add-ins, macros and templates for Microsoft Word
 

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