0
votes

I'm trying to apply a word style to a line of text using vba, so that it will appear in the table of contents. I am having trouble keeping the style contained to the line in question though, for some reason the whole document is picking up the style.

With Selection
.TypeText Text:=headername                 ' This is defined previously,
.HomeKey Unit:=wdLine, Extend:=wdMove   ' This is to move the cursor to the start of the line
.Expand wdLine                           ' This is to select the whole line
.Style = "Heading 2"                     ' this is to define the style of the selected text
.EndKey Unit:=wdLine, Extend:=wdMove      ' This is to unhighlight the text
.InsertBreak Type:=wdLineBreak            ' This is to create a line break    
 End With

For some reason though, the whole document picks up "Heading 2" as it's style. I have tried countless other ways of doing this, but with no luck,

Does anyone know a better way of doing this, or see where I am going wrong?

Thanks

1

1 Answers

6
votes

It's not possible to apply a paragraph style to a line of text, only. It must be applied to a paragraph. Sometimes, a paragraph occupies only a single line, as is likely the case in your scenario - but it's important to recognize the difference.

The problem with your code is that, given the order in which it performs the actions, inserting the break is picking up the style formatting and carrying it forward.

Much more efficient and clear is to work with Word's RANGE object, rather than the current Selection. You can use Selection as the starting point, but from then on your code should rely on the much more predictable Range (also, the user won't see things "jumping around"). For example:

Dim rng as Word.Range
Set rng = Selection.Range
rng.Text = headername & vbCr 'Insert the new para at same time
Set rng = rng.Paragraphs(1).Range 'Only the first para
rng.Style = Word.WdBuiltinStyle.wdStyleHeading2 'language independent
rng.Collapse Word.WdCollapseDirection.wdCollapseEnd 
'focus in new para, which has different formatting