0
votes

I have a requirement where I have to extract two lines of text just after the Table of Contents in a Word Document. The text is hidden and added just for use in VBA.

I did some research and found out that I can extract text from a word Document using the Range object and so I tried hardcoding it and I got the value I wanted by using

MsgBox ActiveDocument.Paragraphs(43).Range.Text

Now this code can work for a specific document but for a new document I don't know where the Table of Contents will end and the exact line number from where I have to extract.

Any help is appreciated and thanks in advance.

2
For non-visible storage of information in a Word document, look into using Word Custom Properties (docs.microsoft.com/en-us/office/vba/api/…) or Word Document Variables (docs.microsoft.com/en-us/office/vba/api/word.document.variables). Both are more robust, secure and easier to use than storing as hidden textJohn Korchok

2 Answers

0
votes

This is slightly tricky because field objects don't have a range so you have to seek the range of the Result of the field. Once you have the result range, you can then get the paragraph range in which it sits, and then, the range of the next paragraph and then when you have that, the text of that paragraph. Sounds complicated but in practise is quite simple when you understand how the Word object model works.

Sub Test()

    Debug.Print GetTextAfterToc

End Sub

Public Function GetTextAfterToc() As String

    Dim myfield As Word.Field
    
    For Each myfield In ActiveDocument.StoryRanges(wdMainTextStory).Fields
    
        If myfield.Type = wdFieldTOC Then
        
            GetTextAfterToc = myfield.Result.Paragraphs(1).Range.Next(unit:=wdParagraph, Count:=1).Text
            Exit Function
            
        End If
        
    Next
    
End Function
0
votes

I found an answer to my question. I am posting it to help someone else with a similar question. Thanks to u/slang4201 for the answer.

This will select the two lines immediately following a TOC.

Dim myField As Field
For Each myField In ActiveDocument.Fields
    If myField.Type = wdFieldTOC Then
        myField.Select
        Selection.Collapse wdCollapseEnd
        Selection.MoveDown unit:=wdLine, Count:=2, Extend:=True
        MsgBox (Selection.Range)
        Exit For
    End If
Next myField
End Sub

However, if the lines you are looking for are hidden, they WILL NOT be selected and found unless you unhide them first.

ActiveDocument.Range.Font.Hidden = False

Hope this helps, and good luck!