Search code examples
c#office-interop

How to generate multiple tables in Word Document programmatically


I am trying to create an MS Word document, containing several tables positioned below each other.

The following code results in error message "Requested Member of the Collection Does Not Exist". I know I am inserting the new tables inside the previous one one, I just don't know how to create a new one below.

object myMissingValue = System.Reflection.Missing.Value;
Word._Application myApp = new Word.Application();
Word._Document myDocument = WordApplication.Documents.Add(ref myMissingValue, ref myMissingValue, ref myMissingValue, ref myMissingValue);
Word.Range myRange = myDocument.Range(ref myMissingValue, ref myMissingValue);

for (int i = 0; i < 5; i++)
{
    myDocument.Tables.Add(myRange, 2, 2, ref myMissingValue, ref myMissingValue);
    Word.Table myTable = WordDocument.Tables[i];
    myTable.Range.Borders.Enable = 1;
    myTable.Rows[1].Cells[1].Range.Text = "Table number " + Convert.ToString(i);
}

Solution

  • I figured the answer. I set the Range to the last index -1 of the document content at the end of each cycle.

    myRange = myDocument.Range(myDocument.Content.End - 1, ref myMissingValue);