Replace text with table of contents.

SmallFry
StarLounger
Posts: 91
Joined: 02 Sep 2018, 23:12

Replace text with table of contents.

Post by SmallFry »

With the code below, I can find the text "Insert Table of Contents Here", but now I would like to delete that text and replace it with a TOC. I have the code for the table of contents, but how can I find the text, delete it, and then replace it?

The code actually deletes the found text, but the TOC does not insert at the beginning of the text that has now been deleted. The text "Insert Table of Contents Here" only appears once in the document.

You might ask why not just put the TOC in the document from the beginning, but this is a document that starts off with two sections which would mean two TOCs. I have found how to build two TOC within one document by using named ranges, but probably not going to work with all users.

Code: Select all

Sub FindAndReplaceWithTOC()
    With ActiveDocument.Range.Find
      .Text = "Insert Table of Contents Here"
      .Replacement.Text = ""
      .Wrap = wdFindStop
      .Execute Replace:=wdReplaceAll
    End With
    Call TableOfContents
End Sub

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Replace text with table of contents.

Post by HansV »

Assuming that the TableOfContents macro inserts the TOC at the current selection, try this version:

Code: Select all

Sub FindAndReplaceWithTOC()
    Selection.HomeKey Unit:=wdStory
    Selection.Find.Execute FindText:="Insert Table of Contents Here"
    Call TableOfContents
End Sub
Best wishes,
Hans

SmallFry
StarLounger
Posts: 91
Joined: 02 Sep 2018, 23:12

Re: Replace text with table of contents.

Post by SmallFry »

Hi Hans, yes exactly, that does it. Thanks again.