VBA Word - Apply a style to a line of text

Jam*_*ham 0 vba ms-word word-style

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
Run Code Online (Sandbox Code Playgroud)

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

Cin*_*ter 5

不能仅将段落样式应用于一行文本。它必须应用于一个段落。有时,一个段落只占一行,这在您的场景中很可能是这种情况 - 但重要的是要认识到差异。

您的代码的问题在于,考虑到它执行操作的顺序,插入中断是获取样式格式并将其向前推进。

使用 Word 的 RANGE 对象而不是当前的选择要高效和清晰得多。您可以使用 Selection 作为起点,但从那时起您的代码应该依赖于更可预测的 Range(而且,用户不会看到“跳跃”的东西)。例如:

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
Run Code Online (Sandbox Code Playgroud)