Thread: [Solved] Delete a table of contents
View Single Post
 
Old Yesterday, 07:18 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,638
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

The "container" if we will call it that is just a BuildingBlock created by Microsoft and they neglected to provide a direct means to work with it within VBA. The building block consists of a TOC Heading line paragraph followed by a paragraph containing the TOC field code.


None of the Artificial Idiot suggestions that I have seen work. So, if we loop through the document TOCs and set a range to the TOC we can capture the TOC field. If we then move the range start back two paragraphs, we can check to see if the first paragraph defines the TOC Heading line (styled with TOC Heading). If so, then we can assume we have captured a TOC in a TOC container and delete if. If not, then we are likely dealing with a stand alone TOC, so restore the range and delete it.


Of course moving or attempting to move a range when a TOC is at the top of a document could result in errors that have to be handled. This isn't pretty, but works for the testing document that I created:

Code:
Sub DeleteTOCs_and_Containers()
Dim oRng As Range
Dim TOC As TableOfContents
Dim lngIndex As Long
  For lngIndex = ActiveDocument.TablesOfContents.Count To 1 Step -1
    Set TOC = ActiveDocument.TablesOfContents(lngIndex)
    Set oRng = TOC.Range.Paragraphs(TOC.Range.Paragraphs.Count).Range
    oRng.MoveStart wdParagraph, -2
    oRng.Select
    Select Case True
      Case oRng.Paragraphs(1).Style = "TOC Heading"
      Case Else
        oRng.MoveStart wdParagraph, 1
    End Select
    On Error Resume Next
    oRng.Delete
    If Err.Number <> 0 Then
      oRng.MoveStart wdParagraph, -1
      oRng.Delete
    End If
    On Error GoTo 0
  Next lngIndex
lbl_Exit:
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote