Thread: [Solved] Delete a table of contents
View Single Post
 
Old Yesterday, 12:48 PM
Charles Kenyon Charles Kenyon is offline Windows 11 Office 2021
Moderator
 
Join Date: Mar 2012
Location: Sun Prairie, Wisconsin
Posts: 9,601
Charles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant futureCharles Kenyon has a brilliant future
Default

Hi Greg,

I ran your code in a document with three TOCs, one a bare field, the other in the Content Controls. None were removed.

The following was offered by John Korchock in response to my question about using SendKeys:

Code:
' Source - https://stackoverflow.com/a/79851355
' Posted by John Korchok
' Retrieved 2025-12-19, License - CC BY-SA 4.0

Sub DeleteAllTOCs()
    Dim f As Field, TOCRange As Range
    Application.ScreenUpdating = False
    Application.StatusBar = "We are deleting tables of content... Be patient..."
    For Each f In ActiveDocument.Fields
        If f.Type = wdFieldTOC Then
            f.Locked = False
            f.Select
            Set TOCRange = Selection.Range
            With TOCRange
                .MoveStart Unit:=wdParagraph, Count:=-1
                .MoveEnd Unit:=wdParagraph, Count:=1
                .Delete
            End With
            Set TOCRange = Nothing
        End If
    Next f
    Application.ScreenUpdating = True
    Application.StatusBar = ""
    Application.ScreenRefresh
    MsgBox "Done."
End Sub

That code does work on my sample. I am still hoping to find an answer about using SendKeys to mimic the Ribbon Accelerator buttons.
Reply With Quote