Office interop - copy a table 2 lines below existing table


  • I am trying to copy an existing table and paste it 2 lines below the existing table.

    Here is the code I have found (and modified):

    oWord.Selection.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdLine, iRow+3); Microsoft.Office.Interop.Word.Range range = oWordDoc.Tables[iTable-1].Range; range.Copy(); Microsoft.Office.Interop.Word.Range rng = oWordDoc.Tables[iTable-1].Range; rng.SetRange(oWordDoc.Tables[iTable-1].Range.End, oWordDoc.Tables[iTable-1].Range.End); Microsoft.Office.Interop.Word.Table tableCopy = oWordDoc.Tables.Add(rng, 4, 7, ref oMissing, ref oMissing); tableCopy.Range.Paste();

    Unfortunately the code is pasting the table as part of the current table instead of a new table, so consequently a new table is not added to the tables collection of the word document.

    I thought this line would accomplish what I wanted:

    oWord.Selection.MoveDown(Microsoft.Office.Interop.Word.WdUnits.wdLine, iRow+3);

    but even though the Selection cursor is moved below the current table, it's pasting the copy as part of the existing one.
    How can I get it to paste the table 2 lines below the end of the existing table please?

    Thursday, December 19, 2013 5:18 PM


  • Hi "Bananas"

    In the code snippet you show us, I think the object rng is going to be inside oWordDoc.Tables[iTable-1].Range. See if it helps to use the following instead of SetRange:

      object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
      rng.Collapse(ref oCollpaseEnd);
    And then try rng.Paste();

    Edit: At this point, please note that the two tables will be adjacent, not separated. To put a paragraph between them:

      rng.Collapse(ref oCollpaseEnd);

    Cindy Meister, VSTO/Word MVP, my blog

    Wednesday, December 25, 2013 2:16 PM

All replies