2009-10-15 65 views
2

有沒有一種方法可以使用VSTO查找WordDocument的所有ContentControl(包括Header,Footers,TextBoxes中的ContentControls)?VSTO找到Word文檔的ContentControls

Microsoft.Office.Tools.Word.Document.ContentContols只返回Main-Document的ContentControls,而不是頭/頁腳內的ContentControls。

回答

0

試試這個:

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

如果沒有在文檔的StoryRanges

0

我處理同樣的問題,但驅動字工作嘗試遍歷所有範圍(contentcontrols)來自MATLAB。此頁由字MVP解決了這個問題對我來說:

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

從本質上講,你必須:

  1. 遍歷所有Document.StoryRanges讓每個故事類型的第一個範圍。
  2. 在每個範圍內,在range.ContentControls上執行您的工作。
  3. range = range.NextStoryRange。
  4. 重複2-4,直到範圍爲空。
3

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; 
    } 
複製