遍历章节名称位于数组中的章节

时间:2019-06-08 21:40:28

标签: arrays vba loops ms-word word-vba

它需要遍历文档并找到章节标题(第一章,第二章等-我相信这应该是一个数组),然后在“章节”一词前插入一个分页符,并在该词后添加两个换行符章节编号。

除了将我的代码复制出20多个章节之外,我如何使用数组查找和替换术语来提高效率?

Sub ChapterHeadings()
'
' ChapterHeadings Macro
'
'
' Copy and paste this for every chapter heading - this works!!!!!!!

    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Style = ActiveDocument.Styles( _
        "Heading 1,Chapter Heading")
    With Selection.Find
        .Text = "Chapter One"
        .Replacement.Text = "^mChapter One^p^p"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

End Sub
{{1}}

查找章节标题时,必须与“章节”数组中设置的内容匹配。 如果有匹配项,它将用分页符(^ m)替换该结果,然后是它最初找到的Chapter标题,然后是两个换行符(^ p ^ p)。

1 个答案:

答案 0 :(得分:1)

未经测试:

Sub ChapterHeadings()
'
' ChapterHeadings Macro
'


    Dim Chapters As Variant, Chapter
    Chapter = Array("Chapter One", "Chapter Two", "Chapter Three", "Chapter Four", "Chapter Five")
    For Each Chapter in Chapters
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        Selection.Find.Replacement.Style = ActiveDocument.Styles( _
        "Heading 1,Chapter Heading")
        With Selection.Find
            .Text = Chapter
            .Replacement.Text = "^m" & Chapter & "^p^p"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    Next Chapter

End Sub