Link to home
Start Free TrialLog in
Avatar of paulmcneil
paulmcneilFlag for United States of America

asked on

Inserting a header in Microsoft Word with VBA

I am creating a report in Word with VBA and I want to change the header when I insert a new section. I want to insert a section break, switch to header view and then send a sequence of TypeText commands to enter a few lines of header text in various formats.

My code successfully inserts the section break (wd is the Word application object):

 wd.Selection.InsertBreak TYPE:=wdSectionBreakNextPage

It then switches to header view and turns off the Same as Previous opiton:

 wd.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
 wd.Selection.HeaderFooter.LinkToPrevious = Not wd.Selection.HeaderFooter.LinkToPrevious

At this point I want to send a series of commands using:

 wd.Selection. + whatever I want to do

for example,

 wd.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
  wd.Selection.Font.Bold = wdToggle
  wd.Selection.Font.Name = "Arial"
  wd.Selection.Font.Size = 14
  wd.Selection.TypeText Text:="Investigations SAR Case Summaries"

but the Selection is not the new empty header that I just inserted with the new section. The Selection is the header from the previous section, so the above code example enters the Bold Arial 14 text "Investigations SAR Case Summaries" at the end of the previous sectio header!

So how do I make the new header (empty) in the new section the Selection object? Thanks.


Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

This command will move the Selection to the header in the next section

Selection.Document.Sections(Selection.Sections(1).Index + 1).Headers(wdHeaderFooterPrimary).Range.select

However, I question whether it is a good idea to use the selection object at all. If you have to start with somewhere that the User selects, then it might be unavoidable, but I prefer to work on the underlying document.

Also do you mean just to toggle the Link to previous, or to set it to false?
Avatar of Billystyx
Billystyx

Selection.Delete 1, 10 'where 10 is the length of the previous header section you want deleted

Put this before the typetext line

Billystyx
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of paulmcneil

ASKER

GrahamSkan, your sample code was very helpful. I was able to incorporate header and range objects to control what I wanted to do with existing header text. Thanks