Hi Vipul,
The location of the TOC is easy to do -- you include a bookmark in the
template so it also appears in the document, and then you set the
location in the code with
Set TOCRange = ActiveDocument.Bookmarks("TOC_here").Range
instead of the line you have.
There are much more serious problems, though. The main one is the
assumption that you can use a character style to mark a part of a line
for inclusion. It won't work. In order to set the TOC options as I
described in my first reply (and note that I did say there "paragraph
style") in a macro, you need a line like
TCTOC.HeadingStyles.Add Style:="TCTOC", Level:=1
If you try this after defining "TCTOC" as a character style, you'll
get a runtime error 5857, "Character styles are not allowed in Table
of Contents".
You could work around this by redesigning the macro so that, instead
of applying a style, it creates a TC field containing the text of the
selection; and instead of being based on styles, the TOC is based on
TC fields (in the TablesOfContents.Add statement, set UseFields:=True
and UseHeadingStyles:=False).
Another problem is that the TableID property of the TOC is not in any
sense the "name" of that particular TOC, as you think. It identifies a
group of TC fields that will be recognized by that TOC field. It
corresponds to the \f switch in the field code. Furthermore, TableID
can't be more than one letter. Therefore, in your code TOCPresent will
always be False and the code will always add another TOC, even when
one is already present.
Read the VBA help topic about the TableOfContents object and the topic
about TOC field codes to learn about this. In any case, there is no
built-in "name" or "tag" for a TOC field -- you may be able to use the
bookmark for this purpose.
Other, less important considerations:
- You don't want to update ActiveDocument.TablesOfContents(1), which
is always the first TOC in the document. Instead, you want
TCTOC.Update.
- The variables styIndex and myStyleIndex serve no purpose, and all
statements that mention them can be deleted.
- The Dim statements for the variables should all come after the Sub
statement, not before it, unless there's a reason to declare them as
module-level global variables (available in all macros within the same
module).
- There are several cases where you've gotten the names of variables
wrong or confused them with other, similar variable names. One thing
that will help is to put the statement Option Explicit at the top of
the module (see
http://www.word.mvps.org/FAQs/MacrosVBA/DeclareVariables.htm and
http://www.word.mvps.org/FAQs/MacrosVBA/MaintainableCode.htm). For
example, after you add the style and assign it to the variable
TCStyle, you then have the statement With myStyle.Font -- that should
be With TCStyle.Font.