WORD - Set header text and tabs / alignment

User avatar
ErikJan
BronzeLounger
Posts: 1324
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

WORD - Set header text and tabs / alignment

Post by ErikJan »

I have VBA code that creates a document header and writes some words there. What I need now is to make sure the text is centered (and I also need something aligned right).

So I need to delete existing tabs (how?), then find the left and right margin (I might know that) and get the middle, then set a center tab (how?). At the right margin I then need a right aligned tab (how?). Looked but finding code doesn't seem easy. Any suggestions or help here?

User avatar
StuartR
Administrator
Posts: 12820
Joined: 16 Jan 2010, 15:49
Location: London, Europe

Re: WORD - Set header text and tabs / alignment

Post by StuartR »

Is TabStop object (Word) enough to get you started?

To find the centre of the page you need

Code: Select all

(ActiveDocument.Sections(1).PageSetup.RightMargin - ActiveDocument.Sections(1).PageSetup.LeftMargin) /2
(air code, not tested
StuartR


User avatar
ErikJan
BronzeLounger
Posts: 1324
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

Re: WORD - Set header text and tabs / alignment

Post by ErikJan »

Thanks... working on it now and will post something when I found the solution.

W.r.t. middle, the right margin = the distance from the right margin...

So the middle should be:

Code: Select all

    With ActiveDocument.PageSetup
        Middle = .LeftMargin + (.PageWidth - .LeftMargin - .RightMargin) / 2
        Debug.Print Middle & " = " & PointsToCentimeters(Middle) & " cm"
    End With

User avatar
ErikJan
BronzeLounger
Posts: 1324
Joined: 03 Feb 2010, 19:59
Location: Terneuzen, the Netherlands

Re: WORD - Set header text and tabs / alignment

Post by ErikJan »

This works (it's somewhat simplified, assuming no different sections, but it works):

Code: Select all

Sub AddHeader()
    With ThisDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range
        With .Paragraphs.TabStops
            .ClearAll
            .Add Position:=MiddlePage, Alignment:=wdAlignTabCenter
            .Add Position:=RightPageMargin, Alignment:=wdAlignTabRight
        End With
        .Text = vbTab & "Highlighted text in the middle" & vbTab
        .HighlightColorIndex = wdYellow
        .Bold = True
    End With
End Sub

Function MiddlePage() As Long
    With ActiveDocument.PageSetup
        MiddlePage = (.PageWidth - .LeftMargin - .RightMargin) / 2
    End With
End Function

Function RightPageMargin() As Long
    With ActiveDocument.PageSetup
        RightPageMargin = .PageWidth - .RightMargin
    End With
End Function