VBA Word - 将样式应用于文本行

VBA Word - Apply a style to a line of text

我正在尝试使用 vba 将文字样式应用于一行文本,以便它出现在 table 的内容中。 不过,我无法将样式包含在相关行中,出于某种原因,整个文档都采用了该样式。

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

但出于某种原因,整个文档采用了 "Heading 2" 的样式。 我已经尝试了无数其他方法来做到这一点,但没有运气,

有没有人知道更好的方法,或者看看我哪里出错了?

谢谢

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

您的代码的问题在于,考虑到它执行操作的顺序,插入分隔符就是选择样式格式并将其向前推进。

使用 Word 的 RANGE 对象比使用当前的 Selection 更有效和清晰。您可以使用 Selection 作为起点,但从那时起您的代码应该依赖更可预测的范围(而且,用户不会看到东西 "jumping around")。例如:

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