Word VBA:获取连续标题之间的范围

时间:2013-02-06 19:24:40

标签: vba word-vba

我查了一些例子,但我不太明白Range对象是如何工作的。我试图遍历每个标题(级别4)并有一个嵌套循环,查看标题之间的所有表格。我无法弄清楚如何设置特定的范围,所以任何帮助将不胜感激。

    Dim myHeadings As Variant
    myHeadings = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)

    For iCount = LBound(myHeadings) To UBound(myHeadings)

      level = getLevel(CStr(myHeadings(iCount)))
      If level = 4 Then

         'This is where I want to set a range between myHeadings(iCount) to myHeadings(iCount+1)
         set aRange = ??


      End If

    Next iCount

2 个答案:

答案 0 :(得分:3)

你在这里正确的方向。 myHeadings变量只是给出了文档中Level 4 Headings的字符串列表。您需要做的是在文档中搜索这些字符串以获得4级标题的范围。

获得每个标题的范围后,您可以检查这些标题之间的范围内的表格。我已经稍微修改了你的代码来做到这一点。还要注意将Option Explicit置于模块顶部以确保声明所有变量的良好做法。

我的代码将告诉您每个4级标题之间有多少个表。注意:它不会在文档的最后一个标题和结尾之间进行检查,我会将其留给您;)

Sub DoMyHeadings()
    Dim iCount As Integer, iL4Count As Integer, Level As Integer, itabCount As Integer
    Dim myHeadings As Variant, tbl As Table
    Dim Level4Heading() As Range, rTableRange As Range

    myHeadings = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)

    'We want to move to the start of the document so we can loop through the headings
    Selection.HomeKey Unit:=wdStory

    For iCount = LBound(myHeadings) To UBound(myHeadings)
        Level = getLevel(CStr(myHeadings(iCount)))
        If Level = 4 Then

            'We can now search the document to find the ranges of the level 4 headings
            With Selection.Find
                .ClearFormatting                                'Always clear find formatting
                .Style = ActiveDocument.Styles("Heading 4")     'Set the heading style
                .Text = VBA.Trim$(myHeadings(iCount))           'This is the heading text (trim to remove spaces)
                .Replacement.Text = ""                          'We are not replacing the text
                .Forward = True                                 'Move forward so we can each consecutive heading
                .Wrap = wdFindContinue                          'Continue to the next find
                .Format = True
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute
           End With

           'Just make sure the text matches (it should be I have a habit of double checking
            If Selection.Text = VBA.Trim$(myHeadings(iCount)) Then
                iL4Count = iL4Count + 1                             'Keep a counter for the L4 headings for redim
                ReDim Preserve Level4Heading(1 To iL4Count)         'Redim the array keeping existing values
                Set Level4Heading(iL4Count) = Selection.Range       'Set the range you've just picked up to the array
             End If
         End If
     Next iCount

    'Now we want to loop through all the Level4 Heading Ranges
    For iCount = LBound(Level4Heading) To UBound(Level4Heading) - 1
        'Reset the table counter
        itabCount = 0

        'Use the start of the current heading and next heading to get the range in between which will contain the tables
        Set rTableRange = ActiveDocument.Range(Level4Heading(iCount).Start, Level4Heading(iCount + 1).Start)

        'Now you have set the range in the document between the headings you can loop through
        For Each tbl In rTableRange.Tables
            'This is where you can work your table magic
            itabCount = itabCount + 1
        Next tbl

        'Display the number of tables
        MsgBox "You have " & itabCount & " table(s) between heading " & Level4Heading(iCount).Text & " And " & Level4Heading(iCount + 1).Text
    Next iCount
End Sub

答案 1 :(得分:1)

您可以使用Goto从一个标题跳转到下一个标题。请参阅下文,了解如何循环使用4级标题。

Dim heading As Range
Set heading = ActiveDocument.Range(start:=0, End:=0)
Do   ' Loop through headings
    Dim current As Long
    current = heading.start
    Set heading = heading.GoTo(What:=wdGoToHeading, Which:=wdGoToNext)
    If heading.start = current Then
        ' We haven't moved because there are no more headings
        Exit Do
    End If
    If heading.Paragraphs(1).OutlineLevel = wdOutlineLevel4 Then

        ' Now this is a level 4 heading. Let's do something with it.
        ' heading.Expand Unit:=wdParagraph
        ' Debug.Print heading.Text

    End If
Loop

不要特别注意“标题4”,因为,

  • 可以使用非内置样式
  • 它不适用于Word的国际版本。

请改为wdOutlineLevel4

现在,要获得整个4级的范围,这里有一个鲜为人知的技巧:

Dim rTableRange as Range
' rTableRange will encompass the region under the current/preceding heading
Set rTableRange = heading.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")

这对于文档中的最后一个标题4或标题3下面的最后一个标题更有效。