none
Can't insert field into table cell - 'command is not available' error RRS feed

  • Question

  • Hi guys!
    I'm using VSTO and C# to create a add-in for Word. So far no big deal, however I got some curious problems with the HeaderFooter section....

    I put a table and some formating into the header of the document.
    When I try to add a Autotext fields (PAGE/NUMPAGE), I got a COM-Exception "command is unavailable".

    This is the code:

    Word.Document doc = this.Application.Documents[1];
    Word.Section s = doc.Sections[1];
    
    Word.Range HeaderRange = s.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
          
    Word.Table t = doc.Tables.Add(HeaderRange,NumRows:2,NumColumns:2,AutoFitBehavior:Word.WdAutoFitBehavior.wdAutoFitWindow);
    
    
    //Error thrown here      
    doc.Fields.Add(t.Cell(2, 2).Range. Word.WdFieldType.wdFieldEmpty, "NUMPAGES", true);
    
    //using this works fine
    //doc.Fields.Add(doc.Range(0). Word.WdFieldType.wdFieldEmpty, "NUMPAGES", true);
    
    

    Yes, there is a document loaded....

    When using a different range, it works.

     

    may somebody give me a hint?

    Wednesday, March 9, 2011 7:58 AM

Answers

  • Hi wom_,

    Don't know how I discovered this (it's been a long time since I solved this problem), but you must redefine your range as follows when in a table:

          wdRange = wdTable.Cell(2, 2).Range
          wdRange = doc.Range(CInt(wdRange.Start), wdRange.End - 1)
    

    Kind regards,

    Carlos Mallen

    • Marked as answer by wom_ Thursday, March 10, 2011 6:49 AM
    Thursday, March 10, 2011 3:29 AM

All replies

  • Hi wom_,

    Don't know how I discovered this (it's been a long time since I solved this problem), but you must redefine your range as follows when in a table:

          wdRange = wdTable.Cell(2, 2).Range
          wdRange = doc.Range(CInt(wdRange.Start), wdRange.End - 1)
    

    Kind regards,

    Carlos Mallen

    • Marked as answer by wom_ Thursday, March 10, 2011 6:49 AM
    Thursday, March 10, 2011 3:29 AM
  • Hi Carlos!

    It works this way. Meanwhile I discovered a workaround by myself.

    But your snippet seems to be more accurate and saved me some line of code, so, thanks for your reply!
    Thursday, March 10, 2011 6:49 AM