首页 > 解决方案 > 我们如何在 Word 文档的起点和终点之间进行复制?

问题描述

这是我正在测试的代码。

Sub CopySummary()
    Dim lngStart As Long
    Dim lngEnd As Long
    Dim docNew As Document
    Selection.HomeKey Unit:=wdStory
    With Selection.Find
        .ClearFormatting
        .Wrap = wdFindStop
        .MatchCase = False
        .Text = "Start"
        If .Execute = False Then
            MsgBox "'Summary' not found.", vbExclamation
            Exit Sub
        End If
        Selection.Collapse Direction:=wdCollapseEnd
        lngStart = Selection.End
        .Text = "End"
        If .Execute = False Then
            MsgBox "'End of Summary' not found.", vbExclamation
            Exit Sub
        End If
        lngEnd = Selection.Start
    End With
    ActiveDocument.Range(lngStart, lngEnd).Copy
    Set docNew = Documents.Add
    docNew.Content.Paste
End Sub

这基本上有效,但问题是“开始”和“结束”在我的文档中出现了几次。此代码仅复制第一次出现的“开始”和“结束”。我想复制所有出现的“开始”和“结束”,以及“开始”和“结束”之间的所有文本。也许循环通过标题或循环通过段落,并在这个级别进行搜索?我对 Word 的 VBA 了解不多。

标签: vbams-word

解决方案


This ended up working for me.

Sub ListPhrases()
    Dim rng As Range
    Dim strPhrases As String
    Set rng = ActiveDocument.Content
    With rng.Find
        .ClearFormatting
        .MatchWildcards = True
        .Wrap = wdFindStop
        .Text = "\Start*\End"
        Do While .Execute
            strPhrases = strPhrases & vbCr & rng.Text
        Loop
    End With
    ActiveDocument.Content.InsertAfter strPhrases
End Sub

推荐阅读