首页 > 解决方案 > 遍历章节名称在数组中的章节

问题描述

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

与其将我的代码复制到 20 多章,不如使用数组来查找和替换术语,从而提高效率?

Sub ChapterHeadings()
'
' ChapterHeadings Macro
'


    Dim Chapter As Variant
    Chapter = Array("Chapter One", "Chapter Two", "Chapter Three", "Chapter Four", "Chapter Five")

    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

End Sub
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

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

标签: arraysvbaloopsms-word

解决方案


未经测试:

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

推荐阅读