在 MS Word 中输入循环页码作为页脚

问题描述 投票:0回答:2

我有一份 200 页长的文档。我想标记页脚,使第一页读取“第 1 页,共 2 页”,第二页读取“第 2 页,共 2 页”,第三页应读取“第 1 页,共 2 页”,依此类推。

我正在尝试使用 VBA 脚本,因为我不想使用“不同的首页”,然后每两页给出分节符。

Sub InsertCyclicFooters()
    Dim doc As Document
    Dim sec As Section
    Dim rng As Range
    Dim i As Integer
    Dim n As Integer
    
    Set doc = ActiveDocument
    n = 2
    
    For Each sec In doc.Sections
        Set rng = sec.Footers(wdHeaderFooterPrimary).Range
        
        i = rng.Information(wdActiveEndAdjustedPageNumber)
        
        i = (i - 1) Mod n + 1
        
        rng.Text = "Page " & i & " of " & n
        
        sec.Range.InsertBreak Type:=wdSectionBreakNextPage
    Next sec
    
    doc.Fields.Update
End Sub

此脚本将每个页面标记为“第 1 页,共 2 页”。

我尝试使用 Ctrl + AF9 更新字段。

vba ms-word
2个回答
1
投票

看看这是不是你想要的:

Sub InsertCyclicFooters()
    Dim doc As Document
    Dim sec As Section
    Dim rng As Range, rngGoto As Range
    Dim i As Integer
    Dim n As Integer
    Dim pageCount As Long, ur As UndoRecord
    
    Set ur = Word.Application.UndoRecord
    ur.StartCustomRecord "InsertCyclicFooters"
    
    Set doc = ActiveDocument
    n = 2
    
    pageCount = doc.Range.Information(wdNumberOfPagesInDocument)
    
    Set rng = doc.Characters(1)
    Do While i < pageCount
        i = rng.Information(wdActiveEndAdjustedPageNumber)
        Set rngGoto = rng.GoTo(wdGoToPage, wdGoToNext, 1)
'        Do Until rngGoto.Information(wdActiveEndPageNumber) = i + 1
'            rngGoto.Move Count:=-1
'        Loop
        
        If i < pageCount Then
            rngGoto.InsertBreak Type:=wdSectionBreakNextPage
            Set rng = rng.Document.Sections(n).Range.Characters(1)
            n = n + 1
        End If
    Loop
    
    n = 2
    Set rngGoto = doc.Characters(1)
    For Each sec In doc.Sections
        
        sec.Footers(wdHeaderFooterPrimary).LinkToPrevious = False
        Set rng = sec.Footers(wdHeaderFooterPrimary).Range
        
        
        'i = rng.Information(wdActiveEndAdjustedPageNumber)
        i = rngGoto.Information(wdActiveEndAdjustedPageNumber)
        
        i = (i - 1) Mod n + 1
        
        rng.Text = "Page " & i & " of " & n
        
        'sec.Range.InsertBreak Type:=wdSectionBreakNextPage
        Set rngGoto = rng.GoTo(wdGoToPage, wdGoToNext, 1)
        
    Next sec
    
    doc.Fields.Update
    
    ur.EndCustomRecord
End Sub

0
投票

您可以仅使用域代码来完成此操作(如果您愿意,也可以不使用分节符)。例如,假设页面实际上编号为 1,2,3,4,...

Page { 1+MOD({ PAGE }+1,2) } of 2

或者,删除空格,

Page{1+MOD(({PAGE}+1,2)} of 2

无论您使用字段还是 VBA+字段,对于偶数页都应该没问题,例如200. 如果你实际上有一个奇数,你可能需要在最后做一些特殊的事情来给你

Page 1 of 1
(分节符可能是最简单的方法)。

全部 {} 需要是特殊字段代码大括号对,您可以使用 ctrl-F9 在 Windows 桌面 Word 上输入。

© www.soinside.com 2019 - 2024. All rights reserved.