如何使用 VBA 代码将从用户输入开始的递增数字添加到 Word 文档的页脚?

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

我正在尝试在 Microsoft Word 中使用 VBA 编写一个宏,该宏将执行以下操作:

  1. 输入起始编号和结束编号。

  2. 将页数插入文档中,即起始页数与结束页数之差减一(以占原始页数)。

  3. 将相应的编号添加到每页的页脚。

因此,如果输入的起始页码为 5,结束页码为 10,则总共需要在文档中插入 5 个新页面。然后,第一页的页脚应该显示“第 5 页”,第二个“第 6 页”,依此类推,一直到“第 10 页”。

此代码可以很好地插入页面,但除此之外,我无法正确插入数字。

Sub InsertPages()
    Dim startPage As Integer
    Dim endPage As Integer
    Dim i As Integer
    
    ' Prompt the user to input the starting and ending page numbers
    startPage = InputBox("Enter the starting page number:", "Starting Page")
    endPage = InputBox("Enter the ending page number:", "Ending Page")
    
    ' Validate input
    If startPage >= endPage Or startPage < 1 Or endPage < 1 Then
        MsgBox "Invalid page numbers. Please enter valid page numbers.", vbExclamation
        Exit Sub
    End If
    
    ' Loop through and insert pages
    For i = startPage To endPage - 1
        Selection.InsertBreak Type:=wdPageBreak
    Next i
End Sub
vba ms-word
1个回答
0
投票

Sub AddIncrementingNumbersToFooter()

' 获取用户输入的起始号码 将起始编号变暗为整数 StartNumber = InputBox("请输入起始数字:", "数字输入")

' 检查输入的号码是否有效 如果 IsNumeric(StartNumber) 那么 ' 转到第一页页脚 ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Select

' Insert the starting number and a bookmark
With Selection
    .TypeText Chr(13) ' Move to a new line
    .InsertAfter "SerialNumber " & StartNumber
    .Bookmarks.Add Name:="SerialNumber"
End With

' Loop through all pages except the first
For i = 2 To ActiveDocument.Sections(1).Range.Pages.Count
    ' Go to the footer of the current page
    ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Select
    ' Move to the bookmark
    Selection.GoTo What:=wdGoToBookmark, Name:="SerialNumber"
    ' Increment the number and update the text
    StartNumber = StartNumber + 1
    Selection.TypeText Chr(13) ' Move to a new line
    Selection.InsertAfter "SerialNumber " & StartNumber
Next i

' Set the focus back to the document
ActiveWindow.Activate

其他 MsgBox "请输入有效的号码。" 结束如果

结束子

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