Hi,
First, fields can be locked, so unlocking is required.
Secondly, TOC is composed of FieldTOC that is attached to the last paragraph mark (a bit like the end paragraph of footnote) so deleting the TOC will never delete the TOC container unless this specific paragraph containing the fields is deleted.
Last, I had further issues if document has multiple TOCs.
So I had a brainstorming session for the dreaded AI and proposal was to:
a) Build a Collection of paragrah(1) (this is the end paragraph)
b) Then delete the whole fieldTOC (this will take care of TOC heading and fields - so no need of dealing with range)
c) And delete that paragraph(1) in reverse
And it works!!
PS. I wonder what is adding in newcollection under "
parasToDelete.Add f.Code.Paragraphs(1)", is it the paragrah number?
Code:
Private Sub DeleteAllTOCs()
Dim toc As TableOfContents, para As Paragraph, _
i As Long, f As Field, parasToDelete As New Collection
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
parasToDelete.Add f.Code.Paragraphs(1)
End If
Next f
For Each f In ActiveDocument.Fields
If f.Type = wdFieldTOC Then
f.Delete
End If
Next f
For i = parasToDelete.count To 1 Step -1
parasToDelete(i).Range.Delete
Next i
Application.ScreenUpdating = True
Application.StatusBar = ""
Application.ScreenRefresh
MsgBox "Done."
Set toc = Nothing
End Sub