编辑代码

Sub 党政公文排版()
    Dim doc As Document
    Set doc = ActiveDocument
    Dim s As Section
    Dim para As Paragraph
    
    ' 清除所有样式格式
    doc.Content.Delete
    
    ' ========== 1. 页面设置 ==========
    With doc.PageSetup
        .TopMargin = CentimetersToPoints(3.7)    ' 上边距37mm
        .BottomMargin = CentimetersToPoints(3.5) ' 下边距35mm
        .LeftMargin = CentimetersToPoints(2.8)   ' 左边距28mm
        .RightMargin = CentimetersToPoints(2.6)  ' 右边距26mm
        .HeaderDistance = CentimetersToPoints(1.5) ' 页眉1.5cm
        .FooterDistance = CentimetersToPoints(2.8) ' 页脚2.8cm(35-7=28mm)
        .DifferentFirstPageHeaderFooter = False
        .OddAndEvenPagesHeaderFooter = True      ' 启用奇偶页不同
    End With

    ' ========== 2. 标题设置 ==========
    Dim titleRange As Range
    Set titleRange = doc.Range(0, 0)
    With titleRange
        .InsertAfter "此处插入标题"
        .Font.Name = "方正小标宋简体"
        .Font.Size = 22           ' 二号字
        .ParagraphFormat.Alignment = wdAlignParagraphCenter
        .InsertParagraphAfter     ' 插入空行
        .InsertParagraphAfter     ' 再插入一行作为正文
    End With

    ' ========== 3. 正文格式设置 ==========
    doc.Content.Font.Name = "仿宋GB2312"
    doc.Content.Font.Size = 16     ' 三号字
    doc.Content.ParagraphFormat.FirstLineIndent = CentimetersToPoints(0.74) ' 首行缩进2字符
    doc.Content.ParagraphFormat.LineSpacingRule = wdLineSpaceExactly
    doc.Content.ParagraphFormat.LineSpacing = 28 ' 固定值28磅

    ' ========== 4. 层次标题设置 ==========
    For Each para In doc.Paragraphs
        With para.Range
            ' 一级标题:黑体
            If .Text Like "[一二三四五六七八九十]、*" Then
                .Font.Name = "黑体"
                .ParagraphFormat.Alignment = wdAlignParagraphLeft
            ' 二级标题:楷体
            ElseIf .Text Like "([一二三四五六七八九十])*" Then
                .Font.Name = "楷体GB2312"
                .ParagraphFormat.Alignment = wdAlignParagraphLeft
            ' 三级标题:仿宋
            ElseIf .Text Like "[0-9].*" Then
                .Font.Name = "仿宋GB2312"
                .ParagraphFormat.Alignment = wdAlignParagraphLeft
            End If
        End With
    Next

    ' ========== 5. 页码设置 ==========
    ' 奇数页页码
    With doc.Sections(1).Footers(wdHeaderFooterPrimary)
        .PageNumbers.Add _
            PageNumberAlignment:=wdAlignPageNumberRight, _
            FirstPage:=False
        .Range.Text = "-"   ' 左一字线
        .Range.Fields(1).Code.Text = "PAGE"
        .Range.InsertAfter "-" ' 右一字线
        .Range.Font.Size = 14   ' 四号字
        .Range.Font.Name = "宋体"
    End With

    ' 偶数页页码
    With doc.Sections(1).Footers(wdHeaderFooterEvenPages)
        .PageNumbers.Add _
            PageNumberAlignment:=wdAlignPageNumberLeft, _
            FirstPage:=False
        .Range.Text = "-"   ' 左一字线
        .Range.Fields(1).Code.Text = "PAGE"
        .Range.InsertAfter "-" ' 右一字线
        .Range.Font.Size = 14   ' 四号字
        .Range.Font.Name = "宋体"
    End With

    MsgBox "公文格式设置完成!", vbInformation
End Sub