Reputation: 53
From an subroutine in Excel, I am trying to create a header in a Word document with two words each with different font formatting however the last font formatting wins. Any help would be appreciated! Below is my current code snippet.
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....
UPDATE: I solved the issue by explicitly setting the range. See code snippet below.
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
Upvotes: 0
Views: 163
Reputation: 25663
This can be done a bit more efficiently / elegantly than the code posted in the "update". Relying on Start
and End
values is always a bit chancy with Word since Word can stick "hidden" content into the text flow. To get to the beginning or end of a Range
it's more reliable to use Collapse
. This will also be faster than doing calculations with values.
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
Upvotes: 1