JLuc01
JLuc01

Reputation: 187

How to combine 2 tables in Word VBA?

I am trying to add a new table to a document and to add this table to the table above, in view to have only one table at the end (in other word, combining 2 tables). When I do it with the code below, the 2 tables join together, but the width is different in spite of the 2 tables having exactly the same width before.

Dim docSource As Document
Dim docTarget As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFileName)
' Fill docTarget with the content of docSource
' Insert selected Table with selected Content
Dim myRange As Object
Set myRange = docTarget.Content
myRange.Collapse Direction:=wdCollapseEnd
myRange.FormattedText = docSource.Tables(1).Range.FormattedText
' Close docSource without saving
docSource.Close (0)
Set docSource = Nothing
Set docTarget = Nothing

Any ideas are welcome!

Note I tried to insert a paragraph between the 2 tables (in this case the 2 tables got the same width), but I don't know how to remove by code this paragraph. If I do it manually, the 2 tables are well aligned.

Upvotes: 0

Views: 844

Answers (2)

JLuc01
JLuc01

Reputation: 187

Thanks to "freeflow", I found a solution based on his suggestion.

myRange.Tables(myRange.Tables.Count).Range.Previous(Unit:=wdParagraph).Select
Selection.Delete

Instead of to delete directly, I select the paragraph, then I delete the selection. When I think about it, it is what I do manually. And curiously, I don't have anymore alignment issue with tables.

I also wondering what is the difference between "Content"and "StoryRanges(wdMainTextStory)", but that's another story.

Upvotes: 0

freeflow
freeflow

Reputation: 4355

You can use the '.Previous' method of the range of the last table to find the preceding paragraph and delete it.

ActiveDocument.StoryRanges(wdMainTextStory).Tables(ActiveDocument.StoryRanges(wdMainTextStory).Tables.Count).Range.Previous(unit:=wdParagraph).Delete

Upvotes: 1

Related Questions