一段落Word VBA中具有不同样式的文本
我想在一行中使用粗体而不是粗体文本.
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
结果,整个文本不是加粗的.
As a result, the entire text is not bold.
虽然使用Selection
对象感觉直观",但是编写代码来操纵Word的准确性不如使用Range
对象.您可以将Range
视为不可见的选择,其重要区别在于
While working with the Selection
object feels "intuitive", it's not as accurate for writing code to manipulate Word as using Range
objects. You can think about a Range
as being an invisible selection, with the important differences that
- 代码可以与多个
Range
对象一起使用 - 用户无法影响
Range
的位置(单击屏幕或按箭头键会更改Selection
) - 跟踪
Range
在代码中任意给定点的位置是可靠的
- code can work with multiple
Range
objects - the user can't affect where a
Range
is (clicking on the screen or pressing arrow keys changes aSelection
) - tracking where a
Range
is at any given point in the code is reliable
更改问题中的代码以使用目标" Range
可能如下所示.
Changing the code in the question to work with a "target" Range
could look as follows.
(请注意,我还为要定义的样式添加了Style
对象.与对象(而不是诸如objWrdDoc.Styles("S3")
之类的结构)一起使用时,它更可靠并且键入的次数更少.)
(Note that I've also added Style
objects for the styles being defined. It's much more reliable and a lot less typing to work with objects, rather than constructs such as objWrdDoc.Styles("S3")
.)
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