word vba:在标题之间选择文字

时间:2014-11-05 17:51:27

标签: vba ms-word

我有一个word文档,其中我想选择从枚举2.3.1开始直到(不包括)标题2.3.2或[文件结束]的标题的全文。如果有更小的'它们之间的小节或图片或表格,也应该被选中。

PS:示例:

... 2.2 Blah Blah 2.3 Blubb Blubb [Start Selection] 2.3.1 Important1 Important2 [Picture: Important3] [Table: Important4] 2.3.1.1 Important 5 Important 6 [Stop Selection] 2.3.2 Blieh

我已尝试浏览每个段落,但这很慢。我之后需要此功能来复制选择(我已经知道如何做了这些; - ))。

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

这似乎运作良好。
调整格式设置,使其仅在给定的格式类型中找到“2.3.1”等。

Sub Macro1()
    Selection.WholeStory
    Selection.Collapse wdCollapseStart

    Selection.Find.ClearFormatting
    Selection.Find.Style = ActiveDocument.Styles("Caption 1")
    With Selection.Find
        .Text = "2.3.1"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = True
    End With
    Selection.Find.Execute
    Selection.Collapse wdCollapseStart

    Dim r1 As Range
    Set r1 = Selection.Range

    ' keep format settings, only change text
    Selection.Find.Text = "2.3.2"
    If Selection.Find.Execute Then
        Selection.Collapse wdCollapseStart
    Else
        Selection.WholeStory
        Selection.Collapse wdCollapseEnd
    End If
    Dim r2 As Range
    Set r2 = ActiveDocument.Range(r1.Start, Selection.Start)
    r2.Select

End Sub

答案 1 :(得分:0)

这是我用来选择标题之间文字的VBA宏。但是,它只在任何级别的任何两个标题之间进行选择。它不包括较小的副标题。

Sub SelectBetweenHeadings()
    With Selection
        .GoTo What:=wdGoToHeading, Which:=wdGoToPrevious
        .Collapse
        Dim curRange As Range
        Set curRange = .Range
        .Extend
        .GoTo What:=wdGoToHeading, Which:=wdGoToNext
        If .Range = curRange Then
            .EndKey Unit:=wdStory
        End If
        .ExtendMode = False
    End With
End Sub