Adding a Field to a Word Table


I ran into an interesting problem trying to add a field to a table cell range from C#. I would get an exception:

The command is not available.

This is because the range you get from a cell includes it’s cell marker and you cannot delete that. So, you have to reset the range by one character (see bolded line below). Like this:

private void insertTableWithField(Word.Range PobjRange)
{
Word.
Table LobjTable = PobjRange.Tables.Add(PobjRange, 2, 1);
LobjTable.Cell(1, 1).Range.Text = “Table with Field”;
Word.Range LobjRange = LobjTable.Cell(2, 1).Range;
LobjRange.SetRange(LobjRange.Start, LobjRange.End – 1);
Word.Field LobjField = LobjRange.Fields.Add(LobjRange);
LobjField.Code.Text = “DOCPROPERTY Author \\* MERGEFORMAT”;
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s