View Single Post
  #2   Report Post  
Posted to microsoft.public.word.tables
Jay Freedman
 
Posts: n/a
Default How to add multiple tables via vbscript?

The reason you're overwriting previous tables with new ones is that you set
objRange = objDoc.Range(), which is literally "the range of the entire
document", and then you add the new table using that range. Therefore the
table replaces anything that's already in the document.

One way to fix it is to add this line immediately after each Set objRange
statement:

objRange.Collapse 0

(In VBA the constant wdCollapseEnd has the value 0. The named constant isn't
available to you in vbscript, so you have to use the numeric value.) That
causes the range to consist of the single point between the last character
and the final paragraph mark.

Instead of the Collapse statement, since you've already moved the selection
to the end of the document with the EndKey statement, you can just replace
each Set objRange = objDoc.Range() statement with this:

Set objRange = objSelection.Range

By the way, this post would have been more on-topic in one of the
programming newsgroups, such as microsoft.public.word.vba.general.

--
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.

Tasin wrote:
Hi,

I'm trying to create a multi-table doc via a vbscript, with some text
between each table (a title effectively). The script I've come up
with adds each of the items, but just overwrites the previous item.
ie adds the first title, then overwrites with a table, then
overwrites that with the next title and so on.

I think I'm missing something pretty simple, just to move the
selction on, but as usual, it's the simple thing that's proving to be
the hardest. My script is listed below for anyone who can help me

Thanks.


Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
Set objSelection = objWord.Selection

objSelection.EndKey wdStory, wdMove

'define table section, including title
objSelection.Font.Size = "12"
objSelection.TypeParagraph()
objSelection.TypeText "title 1"
objSelection.TypeParagraph()
objSelection.EndKey wdStory, wdMove

Set objRange = objDoc.Range()
objDoc.Tables.Add objRange, 1,3
Set objTable = objDoc.Tables(1)
objTable.AutoFormat(16)

Set objSelection = objWord.Selection
objSelection.EndKey wdStory, wdMove

'define table section, including title
objSelection.Font.Size = "12"
objSelection.TypeParagraph()
objSelection.TypeText "title2"
objSelection.TypeParagraph()
objSelection.EndKey wdStory, wdMove

Set objRange = objDoc.Range()
objDoc.Tables.Add objRange, 1, 4
Set objTable = objDoc.Tables(2)
objTable.AutoFormat(6)