Wherein my mistake?

A

avkokin

Hello.
I need to insert field into footer. Field of number pages in active
document and minus 1. That is field: {={numpages}-1}
I try it insert with next code:
sub insPN ()
Dim myRange As Range
Set myRange =
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
Selection.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="=",
PreserveFormatting:=False
Selection.Fields.Add Range:=myRange, Type:=wdFieldEmpty,
Text:="numpages", PreserveFormatting:=False
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.TypeText Text:="-1"
Selection.Fields.Update
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
end sub
I get the mistake.
Wherein my mistake?
Thank you very much for help.
 
J

Jean-Guy Marcil

avkokin said:
Hello.
I need to insert field into footer. Field of number pages in active
document and minus 1. That is field: {={numpages}-1}
I try it insert with next code:
sub insPN ()
Dim myRange As Range
Set myRange =
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range
Selection.Fields.Add Range:=myRange, Type:=wdFieldEmpty, Text:="=",
PreserveFormatting:=False
Selection.Fields.Add Range:=myRange, Type:=wdFieldEmpty,
Text:="numpages", PreserveFormatting:=False
Selection.MoveRight Unit:=wdCharacter, Count:=2
Selection.TypeText Text:="-1"
Selection.Fields.Update
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
end sub
I get the mistake.
Wherein my mistake?

Quite a few...
For example, you set myRange, then you add a field using the myRange object,
and then, immediatley after that, you add another field, using the same range
object, thereby overwriting the first field..
Then, you use a Selection objet, assuming it is connected to your Range
object (because of "Selection.Fields.Add Range:=myRange..."), but is in fact
related to whatever happens to be selected in the document when the code runs.

Nested fields with VBA can be quite tricky... for a complete exlpanation and
different solutions, see
http://word.mvps.org/faqs/macrosvba/NestedFieldsWithVBA.htm
 

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