View Single Post
 
Old 03-16-2023, 05:02 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

A string is not the same thing as a Range and a paragraph range includes a return at the end of it

I'm not a fan of TC fields and you haven't explained why you aren't building the TOC using a style which avoids the need to place a TC field at all. The static TC field means that it will become out of step with the paragraph text or number if either were to change later.
Code:
Sub StaticTC()
  Dim myRange As Range, thisPara As String, currentNumber As String
  Dim spaceChar As String, tcText As String
  spaceChar = " "
  Set myRange = Selection.Paragraphs(1).Range
  myRange.End = myRange.End - 1
  thisPara = myRange.Text  ' This is the current paragraph's text
  currentNumber = myRange.ListFormat.ListString   'will be empty if not an autonumber
  tcText = Trim(currentNumber & spaceChar & thisPara)   'remove leading and trailing spaces
  myRange.Collapse Direction:=wdCollapseEnd
  ActiveDocument.TablesOfContents.MarkEntry Range:=myRange, Entry:=tcText, Level:=1
End Sub
If you absolutely can't build the TOC with styles, perhaps a better approach would be to build the TC field with nested Ref fields so that the TOC entries dynamically update with the current paragraph number and text.
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote