+ -
当前位置:首页 → 问答吧 → word vba 批量增加页码

word vba 批量增加页码

时间:2010-11-10

来源:互联网

有若干word文档,想用vba实现如下目标,请大家帮忙修改代码,部分代码借鉴论坛上朋友们的成果:
1、删除原先页码
2、批量增加页脚页码,三种形式:1.2.3或1/3,2/3,3/3(页数/总页数)或第X页 共Y页;
3、居中,靠左,靠右
Sub 批量增加页码()
Dim mydialog As FileDialog, vrtSelectedItem As Variant, Doc As Document
On Error Resume Next
Set mydialog = Application.FileDialog(msoFileDialogFilePicker)
With mydialog
    .Filters.Clear
    .Filters.Add
    .AllowMultiSelect = True
If .Show = -1 Then
Application.ScreenUpdating = False
For Each vrtSelectedItem In .SelectedItems
Set Doc = Documents.Open(FileName:=vrtSelectedItem, Visible:=False)
With Doc
For Each Section In .Sections '删除页眉页脚
    For Each headerfooter In Section.Footers
    headerfooter.Range.Delete
    Next
Next
With Selection
    .GoTo What:=wdGoToPage, Count:=1
    .InsertBreak Type:=wdSectionBreakContinuous
    .Sections(1).Footers(1).LinkToPrevious = False
    .headerfooter.Range.Delete
With .Sections(1).Footers(1).PageNumbers '添加单一页码
    .RestartNumberingAtSection = True
    .StartingNumber = 1
    .Add PageNumberAlignment:=wdAlignPageNumberRight, firstpage:=True
    .RestartNumberingAtSection = True
    .NumberStyle = wdPageNumberStyleArabic
End With
'以下代码功能未实现
'页眉中插入页码,居中
    .Sections(1).Headers(wdHeaderFooterPrimary).PageNumbers.Add PageNumberAlignment:=Word.wdAlignPageNumberCenter
    Word.wdAlignPageNumberLeft , Word.wdAlignPageNumberRight
'页脚中设置页码或者其他内容
With .Sections(1).Footers(wdHeaderFooterPrimary).Range
    NormalTemplate.AutoTextEntries("第 X 页 共 Y 页").Insert Where:=Range, RichText:=True
    .ParagraphFormat.Alignment = wdAlignParagraphRight '段落右对齐

With .Sections(1).Footers(wdHeaderFooterPrimary).Range   '1/3,2/3,3/3(页数/总页数)
    .Fields.Add Sections(1).Footers(wdHeaderFooterPrimary).Range, , "", True
    .Fields.Add Sections(1).Footers(wdHeaderFooterPrimary).Range, , "Page", True
    Selection.TypeText Text:="/"
    .Fields.Add Sections(1).Footers(wdHeaderFooterPrimary).Range, , "NumPages", True
    .Bold = True
    .ParagraphFormat.Alignment = wdAlignParagraphRight
End With
    .Close True
End With
Next
Application.ScreenUpdating = True
End If
End With
End Sub

作者: xmirage   发布时间: 2010-11-10

分个节,再插入页码或一些域就可解决的,,为什么点点鼠标的操作要写这么多代码呢,不解?

作者: ysdms   发布时间: 2010-11-10