VSTO find ContentControls of Word document

Is there a way to find all ContentControls of a WordDocument (including ContentControls in Headers, Footers, TextBoxes ...) using VSTO?

Microsoft.Office.Tools.Word.Document.ContentContols only returns the ContentControls of the main document, not the one inside the header.

+2


source to share


3 answers


Copied from http://social.msdn.microsoft.com/Forums/is/vsto/thread/0eb0af6f-17db-4f98-bc66-155db691fd70



public static List<ContentControl> GetAllContentControls(Document wordDocument)
    {
      if (null == wordDocument)
        throw new ArgumentNullException("wordDocument");

      List<ContentControl> ccList = new List<ContentControl>();

      // The code below search content controls in all
      // word document stories see http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm
      Range rangeStory;
      foreach (Range range in wordDocument.StoryRanges)
      {
        rangeStory = range;
        do
        {
          try
          {
            foreach (ContentControl cc in rangeStory .ContentControls)
            {
              ccList.Add(cc);
            }
            foreach (Shape shapeRange in rangeStory.ShapeRange)
            {
              foreach (ContentControl cc in shapeRange.TextFrame.TextRange.ContentControls)
              {
                ccList.Add(cc);
              }
            }
          }
          catch (COMException) { }
          rangeStory = rangeStory.NextStoryRange;

        }
        while (rangeStory != null);
      }
      return ccList;
    }

      

+3


source


Try the following:

foreach (Word.ContentControl contentcontrol in this.Application.ActiveDocument.ContentControls)
{
    //Some action on all contentcontrol objects
}

      



If that doesn't work, try iterating across all ranges (for contentcontrols) in the StoryRanges document

0


source


I am dealing with the same problem but driving Word from MATLAB. This Word MVP page solved the problem for me:

http://www.word.mvps.org/FAQs/MacrosVBA/FindReplaceAllWithVBA.htm

Essentially, you should:

  • Go through the entire Document.StoryRanges to get the first range of each story type.
  • Within each range, do your work in the range. The contract.
  • range = range.NextStoryRange.
  • Repeat 2-4 until the range is empty.
0


source







All Articles