Friday, 15 August 2014

vba - Inserting text and fields in Word 2010 header without using .Select -



vba - Inserting text and fields in Word 2010 header without using .Select -

i trying prepare word 2010 page header containing fields filename, save date , page number text between each, so: filename+" "+save date+tab+page number. however, can't seem strings in right places. have far this:

sub createheader() dim myrange range activedocument set myrange = .sections(1).headers(wdheaderfooterprimary).range .fields.add range:=myrange, type:=wdfieldfilename, preserveformatting:=true myrange.collapse wdcollapseend myrange.insertafter (" ") myrange.collapse wdcollapseend .fields.add range:=myrange, type:=wdfieldsavedate, text:="\@ yyyy-mm-dd", preserveformatting:=true myrange.insertafter (chr(9)) myrange.collapse wdcollapseend .fields.add range:=myrange, type:=wdfieldpage, preserveformatting:=true end end sub

however, after executing sub, different parts not intend. instead, show filename+" "+tab+page number+save date. doing wrong here? if @ possible, prefer not resorting .select.

(please note asked a similar question.)

i believe problem here stems fact set myrange variable header text which, when empty, first (empty) character. after add together savedate seems go out of original range. need add together 2 things create code work.

firstly, want collapse end after each insertion need redefine header range (myrange variable) header after inserting savedate.

it's bit ugly next code seems desire. note if don't set lastly wdcollapseend in code doesn't work.

finally, i'd update fields @ end don't have manually yourself.

sub createheader() dim myrange range activedocument set myrange = .sections(1).headers(wdheaderfooterprimary).range .fields.add range:=myrange, type:=wdfieldfilename, preserveformatting:=true myrange.collapse wdcollapseend myrange.insertafter (" ") myrange.collapse wdcollapseend .fields.add range:=myrange, type:=wdfieldsavedate, text:="\@ yyyy-mm-dd", preserveformatting:=true set myrange = .sections(1).headers(wdheaderfooterprimary).range myrange.collapse wdcollapseend myrange.insertafter (chr(9)) myrange.collapse wdcollapseend .fields.add range:=myrange, type:=wdfieldpage, preserveformatting:=true myrange.fields.update end

end sub

vba header field word-2010

No comments:

Post a Comment