Search code examples
excelvbams-wordinsertrow

VBA from Excel to Word add table row in table with merged cells


I have looked all over the internet for a solution to my problem but no answer. What I want to do is insert a row in a Word table using Excel VBA. The table contains some merged cells outside the area I want to insert the rows. What I would do for a table without merged cells is something like this:

Dim WrdApp As Word.Application
Dim docPA As Word.Document
Dim tabelWord As Word.Table

Set WrdApp = GetObject(, "word.Application")
Set docPA = WrdApp.Documents.Open(Application.ActiveWorkbook.Path & "\TabeleCopyV3.doc")
Set tabelWord = docPA.Bookmarks("TabelSOPotential").Range.Tables(1)
tabelWord.Rows(2).Select
WrdApp.Selection.InsertRowsAbove (5)

This works great for tables that have no merged cells. However, if the table has even 2 merged cells (outside the area in which I want to insert the data) then the selection doesn't happen. I cannot even address the table cell using this code:

tabelWord.Rows(2).Cells(1).Range.text = "text"

The only way I can address the cells (and it works) is by using this code:

tabelWord.cell(2, 1).Range.text = "text"

This way I managed to delete rows like this:

tabelWord.cell(2, 1).Delete ShiftCells:=wdDeleteCellsEntireRow

But how then do I insert rows this way? Thank you!


Solution

  • After some years of experience from posting the question, I find that the only solution for tables with vertically merged cells is to Add extra rows in the template document (usually about 20 are enough) and do a FOR loop to delete the empty ones with the deletion code:

    tabelWord.cell(2, 1).Delete ShiftCells:=wdDeleteCellsEntireRow