I'm trying to add a field for a custom document property into a table in a Word document using the Word Interop. However, when I do this I'm getting an error:

"System.Runtime.InteropServices.COMException: 'This command is not available.'"

I've tried multiple ways to get around this, and the code works for just adding the field to a range within the document, but any time I try to add the field to the cell within the table I'm getting the same error. Does anyone know of a way to do this, or what I'm doing wrong.

Some example code of what I'm trying to do is:

Word.Section section = wordDoc.Sections[1];
Word.Range range = section.Range;
Word.Table table = range.Tables.Add(range, 1, 3);
//Format table
table.Cell(1, 1).Range.Fields.Add(table.Cell(1,1).Range, Word.WdFieldType.wdFieldDocProperty,
    "DocPropertyName", true);
1

There are 1 best solutions below

0
On BEST ANSWER

as to my earlier comment, it is indeed that you cannot add a field to the cell.range as a whole: below sample insert a page number in a table in the footer 'foot' as "x of y" where x is current page number and y the total number of pages.

 Dim rng As Range = footerTable.Cell(1, 3).Range.Duplicate
 rng.Collapse(WdCollapseDirection.wdCollapseStart)
 
 Dim fld As Field = foot.Range.Fields.Add(Range:=rng, Type:=WdFieldType.wdFieldPage)

 If fld.Result.Text <> Nothing Then rng.MoveEnd(WdUnits.wdCharacter, Count:=fld.Result.Text.Count)
 
 rng.Collapse(WdCollapseDirection.wdCollapseEnd)
 rng.InsertAfter(Text:=" of ")
 rng.Collapse(WdCollapseDirection.wdCollapseEnd)

 foot.Range.Fields.Add(Range:=rng, Type:=WdFieldType.wdFieldNumPages)

Ps. works with custom property too.