Vba 宏自动为word文档编号

Vba 宏自动为word文档编号,vba,ms-word,Vba,Ms Word,我已经将3000个文档合并到一个word文件中,所有文档都由一个分节符分隔。是否有一个宏可以自动按照0001、0002等行对每个文档进行编号?是的,以下是代码: 查找分节符(^b) 将其更改为手动分页符(^m)及其编号 有关在Word中查找通配符、特殊字符等的详细信息(如^b-分节符;^m-手动分节符): 代码如下: Option Explicit Sub changeSectionsForPageBreaksAndNumbers() Dim i, countSections, s

我已经将3000个文档合并到一个word文件中,所有文档都由一个分节符分隔。是否有一个宏可以自动按照0001、0002等行对每个文档进行编号?

是的,以下是代码:

  • 查找分节符(^b)
  • 将其更改为手动分页符(^m)及其编号
有关在Word中查找通配符、特殊字符等的详细信息(如^b-分节符;^m-手动分节符):

代码如下:

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
    -新行
  • “#”和右(“0000”和“1”,4)
    -结果为#0001。此部分将“1”推到该字符串的右侧,但将其限制为4位

干杯,伙计,非常有帮助。非常好,Christian@Christian,如果这解决了您的问题,您可以将答案勾选为“已接受”。