在 Word 中使用 VBA,如何清除/更新/更改/重新格式化页脚样式

在 Word 中使用 VBA,如何清除/更新/更改/重新格式化页脚样式

我正在尝试在 Word 文档的每一页中插入页脚。有时以下代码有效,有时无效。问题:页脚样式默认为 Header1 或 Header2 或 Body Paragraph 样式。如何让代码清除/更改和/或更新页脚中的默认样式,这样我就可以将代码中的文本插入页脚,而不会出现我一直遇到的格式问题?

Sub FooterInsertion()

    Dim objWord As Object
    Dim objDoc As Object
    Dim objRange As Word.Range
    Dim myTable As Table
    Dim i As Long
    Dim f As Long
    Dim s As String
    Dim auth As String

    auth = InputBox("Type in the Number")
    If auth = "" Then Exit Sub

'    Set objWord = CreateObject("Word.Application")
    Set objWord = Application
    objWord.Visible = True
    Set objDoc = ActiveDocument
    objDoc.PageSetup.OddAndEvenPagesHeaderFooter = False


    For i = 1 To objDoc.Sections.Count
        With objDoc.Sections(i)

            For f = wdHeaderFooterPrimary To wdHeaderFooterFirstPage
                Set objRange = .Footers(f).Range
                s = objRange.Text
                With objRange
                    .ParagraphFormat.Alignment = wdAlignParagraphLeft
                    With .Font
                        .Name = "Arial"
                        .Size = 9
                        .Bold = vbTrue 'wdToggle

                    End With
                    .Text = "CONFIDENTIAL INFORMATION                                                                                  CW" & auth & Chr(11) & _
                            s & Chr(9)
                    .Collapse wdCollapseEnd
                    .Fields.Add Range:=objRange, _
                                Type:=wdFieldEmpty, _
                                PreserveFormatting:=True

                End With


            Next f
        End With
    Next i
End Sub

答案1

我建议使用定义的样式而不是直接格式化页脚文本......

Set objRange.Style="UseYourFooterStyleNameHere"

或者您可以修改页脚的现有默认样式:

Dim objStyle as Style

Set objStyle=objDoc.Styles("UseTheExistingStyleNameHere")

With objStyle
    With .Font
        .NameAscii="+body" ' Uses the document's default body text font
                            ' and the .Font.Name will appear as that font's name
                            ' (e.g., "Calibri", or "Arial", or ...)

        'or hard-code with: .Font.Name = "Arial"
        .Size=9
        .Bold=vbTrue
    End With
    .ParagraphFormat.Alignment=wdAlignParagraphLeft
End With

Set objStyle=Nothing

当然,如果其他地方对其他文本使用了默认页脚样式,那么您也会更改这些地方。

相关内容