【发布时间】:2020-07-06 23:54:47
【问题描述】:
我已将 3000 个文档合并到一个 word 文件中,这些文件都由分节符分隔。是否有一个宏可以自动按照 0001、0002 等为每个文档编号?
【问题讨论】:
我已将 3000 个文档合并到一个 word 文件中,这些文件都由分节符分隔。是否有一个宏可以自动按照 0001、0002 等为每个文档编号?
【问题讨论】:
是的,代码如下:
有关在 Word 中查找通配符、特殊字符等的更多信息(如 ^b - 分节符;^m - 手动分节符): Find and replace text or other items (support.office.com)
代码如下:
Option Explicit
Sub changeSectionsForPageBreaksAndNumbers()
Dim i, countSections, sectionNumber
countSections = ActiveDocument.Sections.Count
'Loop that changes section breaks for page break + # + number of the section (from 2 to last section)
For i = 1 To countSections Step 1
sectionNumber = i + 1
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "^b"
.Replacement.Text = "^m" & "#" & Right("0000" & sectionNumber, 4) & vbCr
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute Replace:=wdReplaceOne
Selection.MoveRight Unit:=wdCharacter, Count:=1
Next
'first number in the beginning of the document
Selection.HomeKey Unit:=wdStory
Selection.InsertBefore "#0001" & vbCr
MsgBox ("Total sections: " & countSections)
End Sub
vbCr — 换行"#" & Right("0000" & "1", 4) — 结果为 #0001。这部分将“1”推到该字符串的右侧,但将其限制为 4 位。【讨论】: