Currently I'm working on improving a translated Word VBA code in VB.net. The program processes 200+ Word documents. So far, the program is running OK. I have an issue with inserting a table that contains images and text (from a template, wTemp
) at the begining of each of the documents (wDoc
). The way it is done now (and in the VBA) uses the clipboard - copy wTemp.Table(1) and paste it at wDoc.range(0,0)
.
However, there are at least two issues with this:
wTemp
needs to be open all the time (not a major issue)What I would like to achieve is described in the following (pseudo) code:
open wTemp(readonly)
dim wTable as word.table = wTemp.tables(1) ' the table I need is the first one
close wTemp(false) ' preferably!
for each wDoc in someCollection
open wDoc
wDoc.Application.Selection.HomeKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove)
' here comes the copy/paste code that works, but I want to replace it with something like this
' insert wTable at current selection point
wDoc.Range.FormattedText = wTable.Range.FormattedText 'thanks to @Oscar-sun
wDoc.save
wDoc.close(false)
next wDoc
wTemp.close(false) ' if I have to keep it open for the duration of the loop
I understand that tables.add()
method allows you to inserts a table with rows/colums, but I don't need to construct the table since it is already in wTemp.
UPDATE
I completely overlooked the .Range.FormattedText
property! Thanks to @Oscar-Sun I updated the code with the missing statement:
wDoc.Range.FormattedText = wTable.Range.FormattedText
.
You can try FormattedText property instead of the clipboard method, refer to my answer here:
Rem implement without the clipboard
myDoc.Range(tbl.Cell(tbl.Rows.count, 1).Range.Start, tbl.Cell(tbl.Rows.count, 1).Range.Start).FormattedText = tbl.Rows(2).Range.FormattedText
So, TRY THIS FIRST! give it a shot !!
open wTemp(readonly)
dim wTable as word.table = wTemp.tables(1) ' the table I need is the first one
close wTemp(false) ' preferably!
for each wDoc in someCollection
open wDoc
wDoc.Application.Selection.HomeKey(Word.WdUnits.wdStory, Word.WdMovementType.wdMove)
' here comes the copy/paste code that works, but I want to replace it with something like this
'insert wTable at current selection point
Selection.Range.FormattedText= wTable.Range.FormattedText'TRY THIS FIRST ! give it a shot !!
rem And remember : Try to avoid using Selection objects, but use Range objects. OK?
wDoc.save
wDoc.close(false)
next wDoc
wTemp.close(false) ' if I have to keep it open for the duration of the loop