我想在一行中使用粗体而不是粗体文本。
With objWrdDoc
.Styles.Add ("S2")
.Styles.Add ("S3")
.Styles("S2").Font.Bold = True
.Styles("S3").Font.Bold = False
End With
With objWrdApp.Selection
.TypeParagraph
.Style = objWrdDoc.Styles("S2")
.TypeText Text:="I want to have bold "
.Style = objWrdDoc.Styles("S3")
.TypeText Text:="and not bold text in one line."
End With
结果,整个文本不是加粗的。
答案 0 :(得分:2)
虽然使用Selection
对象感到“直观”,但是编写代码来操纵Word并不如使用Range
对象那样准确。您可以将Range
视为不可见的选择,其重要区别在于
Range
对象一起使用Range
的位置(点击屏幕或按箭头键会更改Selection
)Range
在代码中任意给定点的位置是可靠的更改问题中的代码以使用“目标” Range
,如下所示。
(请注意,我还为所定义的样式添加了Style
对象。与诸如objWrdDoc.Styles("S3")
之类的结构相比,它更可靠,而且键入的对象更少。)< / p>
Dim S2 as Word.Style, S3 as Word.Style 'As Object if using late-binding
With objWrdDoc
Set S2 = .Styles.Add("S2")
Set S3 = .Styles.Add("S3")
S2.Font.Bold = True
S3.Font.Bold = False
End With
Dim objRange as Word.Range 'As Object if using late-binding
Set objRange = objWrdApp.Selection.Range
With objRange
.Text = vbCr 'Chr(13) = paragraph mark
'The new text should follow the inserted paragraph mark
'Like pressing right-arrow to "collapse" a selection
.Collapse wdCollapseEnd
'When working with ranges, apply the formatting after writing the text
.Text = "I want to have bold "
.Style = S2
.Collapse wdCollapseEnd
.Text = "and not bold text in one line."
.Style = S3
End With