Thread: [Solved] Delete a table of contents
View Single Post
 
Old Yesterday, 02:50 PM
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

Charles,


Well, you are right. That code did nothing with your example.

I think part of the problem will be dealing with TOCs that are in a container as well as those that are not and not with a preceding TOC Heading paragraph.


Both of these seem to work with your examples:

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)
    TOC.Range.Fields(1).Locked = False
    Set oRng = TOC.Range.Fields(1).result
    oRng.MoveStart Unit:=wdParagraph, Count:=-2
    oRng.MoveEnd Unit:=wdCharacter, Count:=1
    Select Case True
      Case oRng.Paragraphs(1).Style = "TOC Heading"
      Case Else
        oRng.MoveStart wdParagraph, 1
    End Select
    oRng.Delete
  Next lngIndex
lbl_Exit:
  Exit Sub
End Sub
Sub DeleteTOCs_and_ContainersII()
Dim TOC As TableOfContents
Dim oRng As Range
Dim lngIndex As Long
  For Each TOC In ActiveDocument.TablesOfContents
    Set oRng = TOC.Range.Paragraphs.First.Previous.Range
    Application.CommandBars.ExecuteMso ("TableOfContentsRemove")
    On Error GoTo Skip
    If oRng.Style = "TOC Heading" Then
      oRng.Delete
    End If
Skip:
  Next TOC
lbl_Exit:
  Exit Sub
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote