Reputation: 43
I´m creating a table with Interop Word. I want to merge two cells in the same column:
table.Rows[2].Cells[7].Merge(table.Rows[3].Cells[7]);
table.Rows[2].Cells[8].Merge(table.Rows[3].Cells[8]);
First line works fine, but in the second, I get this error:
System.Runtime.InteropServices.COMException (0x800A1767): No se puede obtener acceso a determinadas filas de este conjunto porque la tabla tiene celdas combinadas verticalmente.
en Microsoft.Office.Interop.Word.Rows.get_Item(Int32 Index)
What´s the problem ?
table.Rows[2].Cells[7].Merge(table.Rows[3].Cells[7]);
table.Rows[2].Cells[8].Merge(table.Rows[3].Cells[8]);
First line, merge the cell(2,7) and cell(3,7) correctly. In the second line, I get this error:
System.Runtime.InteropServices.COMException (0x800A1767): No se puede obtener acceso a determinadas filas de este conjunto porque la tabla tiene celdas combinadas verticalmente.
en Microsoft.Office.Interop.Word.Rows.get_Item(Int32 Index)
Upvotes: 1
Views: 1958
Reputation: 25663
The problem comes once there are merged cells in a table - certain commands (those that reference rows / columns via an index) do not work when cells are merged because the index value is no longer the same throughout the table. It's annoying, but it's how the Word table interface was designed.
As soon as a table contains merged cells it's necessary to refer to individual cells, using the Table.Cell
property. The arguments for this property are rowIndex
and columnIndex
. Unlike the Rows
and Columns
properties, these work, but it's important to realize that, as soon as a table contains some merged cells, certain cells will "not exist".
In the following example, which performs the task described in the question, the span of rows is a given. The columns over which the merging should be repeated is in an array. The array is looped from the back to the front to ensure that the cells referenced are correct.
C#
Word.Table tbl = doc.Tables[1];
Word.Cell cel = null;
int rowSpanStart = 2;
int rowSpanEnd = 3;
int[] aColIndex = {4, 6};
int colIndex;
for (int i = aColIndex.Length; i > 0; i = i -1)
{
colIndex = aColIndex[i-1];
cel = tbl.Cell(rowSpanStart, colIndex);
cel.Merge(tbl.Cell(rowSpanEnd, colIndex));
}
VBA:
Sub MergeCellsVertically()
'Merge cells vertically in multiple columns
Dim tbl As Word.Table
Dim cel As Word.Cell
Dim rowSpanStart As Long, rowSpanEnd As Long, aColIndex() As Variant
Dim colIndex As Long, i As Long
rowSpanStart = 2
rowSpanEnd = 3
aColIndex = Array(4, 6)
Set tbl = ActiveDocument.Tables(1)
For i = UBound(aColIndex) To LBound(aColIndex) Step -1
colIndex = aColIndex(i)
Set cel = tbl.Cell(rowSpanStart, colIndex)
cel.Merge MergeTo:=tbl.Cell(rowSpanEnd, colIndex)
Next i
End Sub
Upvotes: 3