Adding a table of contents to a Microsoft Word Document using vbs


I am attempting to write a vbs script to create a word document that also contains a Table of Contents. I am able to insert a Table of Contents but am unable to populate the table.

Set oInfo = Dictionary.Items("Use Case")
    For Each oInfo in oInfo

        Set entryRange = objSelection.Range
        objDoc.TablesOfContents.MarkEntry entryRange, oInfo("Name"), oInfo("Name"), W, 1
        objSelection.TypeText "Info" + vbNewline + oInfo("Name")

This results in the Table of Contents being inserted properly but only displays "No table of contents entries found." Also, at the end of the document, I get weird unformatted text that looks something like this: {TC "Info1" \f C \| "1"} This gets repeated for each object that I iterate through in the For loop with the correct title for each section. I feel like I am on the right track, but I don't know enough about the TablesOfContents object to do what I would like to do. I believe one of the main problems is the TableId field in the markEntry function.


When you use MarkEntry, Word inserts a { TC } field. That's what those "weird unformatted text" things are. They do not have a visible result so if you toggle to field results view (Alt-F9 on Windows Word) and do not show hidden text, they will disappear altogether. So they are typically things that would be added after the document is fully populated, at the appropriate places in the document. I would guess that most ToCs actually grab their entries from either Heading levels or Outline levels. If you go into the relevant parts of Word itself and play around with the various ToC options, you should be able to get a better idea of how these things work.

When you insert the TOC, you also get a field. At the monment your code is probably inserting

{ TOC \o "1-9" }

That will get entries from paragraphs with Outline levels 1-9. But it won't insert entries from the TC fields. For that, you need (at least)

{ TOC \f C }

(since C is the identifier you are using in yourTC fields.)

You can do that in VBA code using

objDoc.TablesOfContents.Add Range:=tocRange, UseFields:=True, TableID:="C"

If you still need to bring in entries from the "Outline levels" then you need to set the appropriate parameter in the .Add method to True.

At some point in your code, you may also need to locate the TOC field and "update" it.

As an aside, if you cannot access all the field facilities that you need via the object model's .Add and .MarkEntry fields, it is also possible to insert most field codes more directly, e.g. by adding a field of type "wdFieldEmpty" to a range and providing its field code.

Recent Tips

  1. Change locale in android app (onto Hindi)
  2. How do I stop selenium automation if 20% or 1st 20 test cases test methods are failed?
  3. Sharepoint with silverlight app
  4. What's the best way to write robots.txt for github pages using multiple repos?
  5. Biopython: Cant use .count() for biopython
  6. How can I find out the token balance of an address?
  7. ref value is undefined in vue (modal, textarea, $refs)
  8. Azure - HDInsight Hbase Data Insertion Failed
  9. SignalR overwriting OnConnected(), OnDisconnected()
  10. DatePickerDialog displays with two borders
  11. "type 'double' is not a subtype of type 'int' in type cast" error in flutter. What should i do?
  12. hiding the autocomplete list when user click outside the textbox is not working as expected
  13. JSF IceFaces basic problem with redisplaying input value
  14. How to validate material ui TextField in reactjs?
  15. Go and MongoDB connection won't work with panic log "no reachable server"
  16. WordPress Posts Pagination Not Working
  17. F# sprintf won't print in interactive console
  18. Spring Integration get FTP files recursively with outbound-gateway
  19. Jade mixins not getting working from external file
  20. Can not access defined exports from the webpack bundle?
  21. Completely new to Node.js - API Programming
  22. Formatting Compare-Object Ouput
  23. Add dynamically added textbox value from User Control to main form
  24. Create a ByteBuf in Netty 4.0
  25. Is it possible to do computation before super() in the constructor?
  26. Q-learning Updating Frequency
  27. Wrong reload order when using Gulp and browserSync
  28. I use hugo build static page. But don't have content
  29. How to change background color and set bar colors based on conditional formatting in VBA?
  30. Problem when comparing two numeric values in SAS