简体   繁体   English

如何获取Word VBA中标题1之后的列表?

[英]How to get a list that is immediately after heading 1 in Word VBA?

The following shows pattern of a very long document: 以下显示了一个很长文档的模式:

<heading1>
<numberedlist>
<heading2>
<numberedlist>
<heading3>
<numberedlist>

When I use Document.Lists I get all the lists in the document. 当我使用Document.Lists我得到了文档中的所有列表。 When Iterate using Document.Paragraphs where Document.Paragraphs(i).Style = "Heading 1" I get all the headings. 当使用Document.Paragraphs Document.Paragraphs(i).Style = "Heading 1"迭代Document.Paragraphs ,我得到了所有的标题。

But What I want is the List (not paragraph of the list) which is immediately after "Heading 1" 但我想要的是紧接在“标题1”之后的列表(不是列表中的段落)

Assuming that your document can look like one on the picture below: 假设您的文档看起来像下图中的文档:

在此输入图像描述

Using this proposed code you would be able to select first list (immediate after heading) and other similar lists located below Heading but not the second (there is additional paragraph between heading and list- for that situation see additional comments inside code). 使用此提议的代码,您将能够选择第一个列表(标题后立即)和位于标题下方但不是第二个的其他类似列表(标题和列表之间还有其他段落 - 对于该情况,请参阅代码中的其他注释)。

Sub List_after_Heading()

    Dim rngLIST As Range
    Set rngLIST = ActiveDocument.Content

    With rngLIST.Find
        .Style = "Heading 1"   '<--change into your Heading name
        .Forward = True
        .Wrap = wdFindStop
    End With

    Do
        rngLIST.Find.Execute
        If rngLIST.Find.Found Then

            'I assume that list start in NEXT paragraph, if not, it wouldn't be found
            'or you need to change part of line into .Next.Next paragraphs,
            'alternatively some looping would be needed here

            'we check if paragraph next to Heading contains a list
            If rngLIST.Paragraphs(1).Next.Range.ListParagraphs.Count > 0 Then
                'we have the list, but it's not easy to select at once
                Dim iLIST As List
                For Each iLIST In ActiveDocument.Lists
                    If iLIST.Range.Start = rngLIST.Paragraphs(1).Next.Range.Start Then
                        'here we have it... selected
                        iLIST.Range.Select

                        'or any other of your code here
                    End If
                Next
            End If
        End If
    Loop While rngLIST.Find.Found

End Sub

I use bookmarks to identify the Headings and then simply return the text between them. 我使用书签来识别标题,然后简单地在它们之间返回文本。 But I am not sure by what you mean by But What I want is the List (not paragraph of the list) 但我不确定你的意思But What I want is the List (not paragraph of the list)

ScreenShot 截图

在此输入图像描述

Code

Option Explicit

Sub Sample()
    Dim MyRange As Range

    Selection.HomeKey Unit:=wdStory

    On Error Resume Next
    ActiveDocument.Bookmarks("MYStartBookMark").Delete
    ActiveDocument.Bookmarks("MYEndBookMark").Delete
    On Error GoTo 0

    '~~> Find Heading 1
    With Selection.Find
        .ClearFormatting
        .Style = ActiveDocument.Styles("Heading 1")
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .Execute
    End With

    '~~> Move one space to the right
    Selection.MoveRight Unit:=wdCharacter, Count:=1

    '~~> Insert the start Book mark
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:="MYStartBookMark"
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    '~~> Find Heading 2
    With Selection.Find
        .ClearFormatting
        .Style = ActiveDocument.Styles("Heading 2")
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .Execute
    End With

    '~~> Move one space to the left
    Selection.MoveLeft Unit:=wdCharacter, Count:=1

    '~~> Insert the end Book mark
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:="MYEndBookMark"
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    '~~> Identify the range between the Start BookMark and End BookMark
    Set MyRange = ActiveDocument.Range
    MyRange.Start = MyRange.Bookmarks("MYStartBookMark").Range.End
    MyRange.End = MyRange.Bookmarks("MYEndBookMark").Range.Start

    '~~> This gives you that text
    Debug.Print MyRange.Text

    '~~> Delete the BookMarks
    On Error Resume Next
    ActiveDocument.Bookmarks("MYStartBookMark").Delete
    ActiveDocument.Bookmarks("MYEndBookMark").Delete
    On Error GoTo 0
End Sub

Result 结果

在此输入图像描述

OTHER TESTS 其他测试

One might say that what if we do not know what the next heading is? 有人可能会说,如果我们不知道下一个标题是什么呢? Which is a fair point as we can have two more scenarios. 这是一个公平的观点,因为我们可以有两个场景。 Let me cover them together 让我一起掩盖他们

  1. After Heading 1, we have Heading 3 在标题1之后,我们有标题3
  2. The last Heading in a document is Heading 1 and after that there are no headings. 文档中的最后一个标题是标题1,之后没有标题。

MODIFIED CODE 修改后的代码

Option Explicit

Sub Sample()
    Dim MyRange As Range
    Dim MyArray
    Dim strOriginal As String, strTemp As String
    Dim numDiff As Long, i As Long, NextHd As Long
    Dim NoNextHeading As Boolean

    Selection.HomeKey Unit:=wdStory

    On Error Resume Next
    ActiveDocument.Bookmarks("MYStartBookMark").Delete
    ActiveDocument.Bookmarks("MYEndBookMark").Delete
    On Error GoTo 0

    '~~> Get all the headings in the array
    NoNextHeading = True

    For i = LBound(MyArray) To UBound(MyArray)
        strOriginal = RTrim$(MyArray(i))
        strTemp = LTrim$(strOriginal)
        numDiff = Len(strOriginal) - Len(strTemp)
        numDiff = (numDiff / 2) + 1
        '~~> If heading one is found and it is not the last heading
        '~~> in the array then find what is the next heading
        If numDiff = 1 And i <> UBound(MyArray) Then
            strOriginal = RTrim$(MyArray(i + 1))
            strTemp = LTrim$(strOriginal)
            numDiff = Len(strOriginal) - Len(strTemp)
            numDiff = (numDiff / 2) + 1
            NextHd = numDiff
            NoNextHeading = False
            Exit For
        End If
    Next i

    '~~> Find Heading 1
    With Selection.Find
        .ClearFormatting
        .Style = ActiveDocument.Styles("Heading 1")
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .Execute
    End With

    '~~> Move one space to the right
    Selection.MoveRight Unit:=wdCharacter, Count:=1

    '~~> Insert the start Book mark
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:="MYStartBookMark"
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    If NoNextHeading = False Then
        '~~> Find Heading NextHd
        With Selection.Find
            .ClearFormatting
            .Style = ActiveDocument.Styles("Heading " & NextHd)
            .Text = ""
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindContinue
            .Format = True
            .Execute
        End With

        '~~> Move one space to the left
        Selection.MoveLeft Unit:=wdCharacter, Count:=1
    Else
        '~~> Move to the end of the document
        ActiveDocument.Characters.Last.Select
        Selection.Collapse
    End If

    '~~> Insert the end Book mark
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:="MYEndBookMark"
        .DefaultSorting = wdSortByName
        .ShowHidden = False
    End With

    '~~> Identify the range between the Start Book Mark and End BookMark
    Set MyRange = ActiveDocument.Range
    MyRange.Start = MyRange.Bookmarks("MYStartBookMark").Range.End
    MyRange.End = MyRange.Bookmarks("MYEndBookMark").Range.Start

    '~~> This give you that text
    Debug.Print MyRange.Text

    '~~> Delete the BookMarks
    On Error Resume Next
    ActiveDocument.Bookmarks("MYStartBookMark").Delete
    ActiveDocument.Bookmarks("MYEndBookMark").Delete
    On Error GoTo 0
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Word VBA - 如何插入标题编号的引用; 标题文字; 要评论的列表项编号和列表项页码? - Word VBA - How to insert references of heading number; heading text; list item number and list item page number to comment? VBA 更改 MS-Word 中的标题编号 - VBA Change Heading Number in MS-Word 将VBA中的标题样式从Excel应用于Word - Apply heading style in VBA from Excel to Word vba word 宏将字符串放入现有标题 - vba word macro to put a string to an existing Heading WORD VBA插入列表后的文本 - WORD VBA to INSERT text after a list 使用 VBA 在 MS Word 中使用通配符搜索循环获取标题信息 - Get heading information using a wild card search loop in MS Word using VBA 如何通过VBA检测文档中的上一个标题是标题1还是标题7 - How to detect if the previous heading in the document is heading 1 or heading 7 through VBA 如何按位置顺序从Word文档到数组获取所有书签元素的列表:VBA / Word - How to get list of all bookmark-elements from a Word document to an array in order by location: VBA / Word 如何在内容控制(在Word中)后立即向表添加标题? - How to add caption to a Table immediately after Content Control (in Word)? 使用VBA代码如何从Word文档中提取每个标题下的非HTML数据内容 - Using VBA code how to extract Non HTML data content residing under each heading from a word document
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM