MS Word VBA 将文本框附加到偶数和奇数 header

MS Word VBA attaching a text box to even and odd header

我创建了这段代码来让我的文本框出现在奇数和偶数 header 中,但是文本框总是附加到文档的 body 而不是在 header.

Dim ndx As Integer
Dim line As String
Dim lineChar As Integer
Dim pages As Integer
Dim Box As Shape


'Since the odd/even headers are different, we need to set them twice
For ndx = 1 To 2 'put back to 1 to 2

    If (ActiveDocument.ActiveWindow.Panes(1).pages.Count >= ndx) Then
  
        Selection.GoTo wdGoToPage, wdGoToAbsolute, ndx
        ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

        Set HeaderRange = ActiveDocument.Sections.Item(1).Headers(wdHeaderFooterEvenPages).Range

        HeaderRange.Text = " "

        If ndx = 1 Then
        
            Set Box = ActiveDocument.Shapes.AddTextbox( _
                Orientation:=msoTextOrientationHorizontal, _
                Left:=InchesToPoints(1), Top:=InchesToPoints(0.5), Width:=InchesToPoints(4.8), Height:=InchesToPoints(0.37))
            
        Else
        
            Set Box = ActiveDocument.Shapes.AddTextbox( _
                Orientation:=msoTextOrientationHorizontal, _
                Left:=300, Top:=50, Width:=500, Height:=20)
            
        End If
   
        
        Box.TextFrame.TextRange.Bold = True
        Box.TextFrame.TextRange.Font.Size = 8
        Box.TextFrame.TextRange.Text = "This is a sample policy from another school district. Contents do not necessarily reflect official " & _
            vbCrLf & "MSBA policy, represent MSBA legal advice or service, and are not intended for exact replication."
                      
    End If
   
Next ndx

感谢您的帮助。

您的代码无效,因为它将文本框添加到文档 [ActiveDocument.Shapes.AddTextbox] 而不是 header。下面的代码对我有用。

Sub TextBoxInHeader()
    Dim Box As Shape
    Dim ndx As Integer

    For ndx = 1 To 3 Step 2

        With ActiveDocument.Sections(1).Headers(ndx)
            .Range.Text = " "
            If ndx = 1 Then 'Primary (odd pages) header
                Set Box = .Shapes.AddTextbox( _
                    Orientation:=msoTextOrientationHorizontal, _
                    Left:=InchesToPoints(1), Top:=InchesToPoints(0.5), Width:=InchesToPoints(4.8), Height:=InchesToPoints(0.37))
            Else    'Even pages header
                Set Box = .Shapes.AddTextbox( _
                    Orientation:=msoTextOrientationHorizontal, _
                    Left:=300, Top:=50, Width:=500, Height:=20)
            End If
        End With
   
        With Box.TextFrame.TextRange
            .Bold = True
            .Font.Size = 8
            .Text = "This is a sample policy from another school district. Contents do not necessarily reflect official " & _
                vbCrLf & "MSBA policy, represent MSBA legal advice or service, and are not intended for exact replication."
        End With
                
    Next ndx
End Sub