name: Word批量格式统一工具 description: 使用VBA宏批量统一多个Word文档的格式(字体、段落、页边距、标题样式等),适合报告、标书、合同等大批量文档的标准化处理。 version: 1.0.0 author: 技能开发团队 tags: [Word, VBA, 批量处理, 格式统一, 宏]
本技能提供一套完整的 VBA 宏代码及操作指南,帮助您在 Microsoft Word 中批量处理多个文档的格式。只需选择目标文件夹,宏将自动遍历所有 .docx 文件,统一设置页面、字体、段落、标题样式等,极大提升排版效率。
Alt + F11 打开 VBA 编辑器。```vba Sub BatchFormatUnify() Dim folderPath As String Dim file As String Dim doc As Document Dim folderDialog As FileDialog Dim i As Long
Set folderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With folderDialog
.Title = "请选择包含Word文档的文件夹"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
folderPath = .SelectedItems(1)
End With
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
file = Dir(folderPath & "*.docx")
i = 0
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While file <> ""
Set doc = Documents.Open(folderPath & file, AddToRecentFiles:=False, Visible:=False)
Call UnifyFormat(doc)
doc.Save
doc.Close
i = i + 1
file = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "已完成 " & i & " 个文档的格式统一!", vbInformation
End Sub
Sub UnifyFormat(doc As Document) With doc ' 页面设置(A4,页边距上下2.54cm,左右3.17cm) With .PageSetup .PaperSize = wdPaperA4 .TopMargin = CentimetersToPoints(2.54) .BottomMargin = CentimetersToPoints(2.54) .LeftMargin = CentimetersToPoints(3.17) .RightMargin = CentimetersToPoints(3.17) End With
' 遍历所有段落
Dim para As Paragraph
For Each para In .Paragraphs
para.Range.Font.Reset
With para
.Alignment = wdAlignParagraphLeft
.LineSpacingRule = wdLineSpace1pt5
.FirstLineIndent = CentimetersToPoints(0.74)
.SpaceBefore = 0
.SpaceAfter = 0
' 标题1样式居中、黑体、二号
If .Style = "标题 1" Or .Style = "Heading 1" Then
.Alignment = wdAlignParagraphCenter
.Range.Font.Name = "黑体"
.Range.Font.Size = 22
End If
' 正文样式宋体、小四
If .Style = "正文" Or .Style = "Normal" Then
.Range.Font.Name = "宋体"
.Range.Font.Size = 12
End If
End With
Next para
.Fields.Update
End With
End Sub
这个技能质量中等偏上,胜在功能实用——能批量统一 Word 文档的格式,省去重复排版的麻烦。说明写得清楚,新手跟着步骤也能上手。不过它没有考虑出错的可能,万一某个文件打不开或处理失败了,整个流程就会中断,而且操作前没有自动备份,万一效果不满意就麻烦了。总体来说适合有批量处理需求的用户使用,但建议先备份原文件再用。