1
votes

Using VBA I'm able to insert text in a Word document header:

Set HeaderRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range

HeaderRange.Text = "header text'

But I want to be able to add multiple lines of text to the header, each with it's own style applied to it.

One way I found to do it was as follows:

Set HeaderRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterPrimary).Range

HeaderRange.Text = "Line One Text" & vbNewLine & "Line Two Text"  & vbNewLine & "Line Three Text"

' set the ranges based on sentences
Set NameRange = HeaderRange.Sentences(1)
Set TitleRange = HeaderRange.Sentences(2)
Set AddressRange = HeaderRange.Sentences(3)

' set the styles for each part
NameRange.Style = "title"
TitleRange.Style = "strong"
AddressRange.Style = "emphasis"

That basically works, but if there is a period (.) anywhere in one of the lines of text, that causes a problem.

Is there a better way that I can delimit the text to put into the header into multiple parts and apply a different style to each part?

1

1 Answers

0
votes

The Range.Sentences collection is sensitive to the position of the periods, these mark the end of a sentence. The Range.Paragraphs collection is not, but rather to the positions of the vbNewLine, which is obviously what you want.

Set NameRange = HeaderRange.Paragraphs(1).Range
Set TitleRange = HeaderRange.Paragraphs(2).Range
Set AddressRange = HeaderRange.Paragraphs(3).Range