C# VSF用于查找Word文档的内容控件

C# VSF用于查找Word文档的内容控件,c#,ms-word,vsto,C#,Ms Word,Vsto,有没有办法使用VSTO查找WordDocument的所有ContentControl(包括页眉、页脚、文本框中的ContentControl…) Microsoft.Office.Tools.Word.Document.ContentControl仅返回主文档的ContentControl,而不返回页眉/页脚中的ContentControl。尝试以下操作: foreach (Word.ContentControl contentcontrol in this.Application.Active

有没有办法使用VSTO查找WordDocument的所有ContentControl(包括页眉、页脚、文本框中的ContentControl…)

Microsoft.Office.Tools.Word.Document.ContentControl仅返回主文档的ContentControl,而不返回页眉/页脚中的ContentControl。

尝试以下操作:

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

如果这不起作用,试着在文档的

中的所有范围(对于contentcontrols)上迭代,我正在处理相同的问题,但要从MATLAB中驱动Word。这个页面由一个单词MVP为我解决了这个问题:

基本上,你必须:

  • 循环遍历所有Document.StoryRanges以获取每个故事类型的第一个范围
  • 在每个范围内,对range.ContentControls执行您的工作
  • range=range.NextStoryRange
  • 重复2-4,直到量程为空
  • 抄袭

    公共静态列表GetAllContentControls(文档wordDocument) { if(null==wordDocument) 抛出新的ArgumentNullException(“wordDocument”); List ccList=新列表(); //下面的代码搜索内容控件中的所有 //word文档故事请参见http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm 牧场故事; foreach(wordDocument.StoryRanges中的范围) { rangeStory=范围; 做 { 尝试 { foreach(rangeStory.ContentControls中的ContentControl cc) { ccList.Add(cc); } foreach(rangeStory.shaperage中的Shape shaperage) { foreach(ShaperAge.TextFrame.TextRange.ContentControls中的ContentControl cc) { ccList.Add(cc); } } } 捕获(COMException){} rangeStory=rangeStory.NextStoryRange; } while(rangeStory!=null); } 返回CCL列表; }
    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;
        }