在Word标头中使用两种字体格式的问题

时间:2019-02-27 16:17:58

标签: excel vba ms-word

从Excel的子例程中,我试图在Word文档中创建一个标题,其中包含两个具有不同字体格式的单词,但是最后一种字体格式会获胜。任何帮助,将不胜感激!以下是我当前的代码段。

With myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
    .Font.Name = "Courier New"
    .Font.Size = 10
    .Font.Bold = True
    .Font.Color = wdColorGreen
    .text = "TEXT LINE 1" & vbLf

    .Font.Name = "Calibri Light"
    .Font.Size = 16
    .Font.Bold = False
    .Font.Color = wdColorBlack
    .text = .text & "TEXT LINE 2"
    ....the rest of the code....

更新:我通过明确设置范围来解决此问题。请参见下面的代码段。

With myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
    .Start = 0
    .text = "TEXT LINE 1" & vbLf
    .End = Len(.text)
    .Font.Name = "Courier New"
    .Font.Size = 10
    .Font.Bold = True
    .Font.Color = wdColorGreen
    .ParagraphFormat.Alignment = wdAlignParagraphCenter

    .Start = Len(.text) + 1
    .text = "TEXT LINE 2"
    .End = Len(.text) + .Start
    .Font.Name = "Calibri Light"
    .Font.Size = 16
    .Font.Bold = False
    .Font.Color = wdColorBlack

1 个答案:

答案 0 :(得分:1)

与“更新”中发布的代码相比,这可以更高效/更轻松地完成。依靠StartEnd values 对于Word总是有点困难,因为Word可以将“隐藏”的内容粘贴到文本流中。要到达Range的开头或结尾,使用Collapse更为可靠。这也比使用值进行计算要快。

Dim rng as Word.Range
Set rng = myDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range
With 
    '.Start = 0 'Not necessary as this will be the default position
    .text = "TEXT LINE 1" & vbLf
    '.End = Len(.text) 'Also not necessary, see further down...
    .Font.Name = "Courier New"
    .Font.Size = 10
    .Font.Bold = True
    .Font.Color = wdColorGreen
    .ParagraphFormat.Alignment = wdAlignParagraphCenter

    .Collapse wdCollapseEnd 'put focus at end of range

    '.Start = Len(.text) + 1 'calculation not necessary as range has been collapsed
    .text = "TEXT LINE 2"
    '.End = Len(.text) + .Start 'not necessary
    .Font.Name = "Calibri Light"
    .Font.Size = 16
    .Font.Bold = False
    .Font.Color = wdColorBlack
End With