Wednesday, January 5, 2011

C#: Find all ContentControls in a Word document

public static List GetAllContentControls(ref Word.Document document)
{
List ccArray = new List();
//Body
for (int i = 1; i < document.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(document.ContentControls.get_Item(ref objIdx));
}
//Headers
foreach (Word.Section section in document.Sections)
{
for (int i = 1; i < section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].Range.ContentControls.get_Item(ref objIdx));
}
for (int i = 1; i < section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.ContentControls.get_Item(ref objIdx));
}
for (int i = 1; i < section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ContentControls.get_Item(ref objIdx));
}
}
//Footers
foreach (Word.Section section in document.Sections)
{
for (int i = 1; i < section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].Range.ContentControls.get_Item(ref objIdx));
}
for (int i = 1; i < section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.ContentControls.get_Item(ref objIdx));
}
for (int i = 1; i < section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ContentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ContentControls.get_Item(ref objIdx));
}
}
//Textboxes
for (int j = 1; j < document.Shapes.Count + 1; j++)
{
object idx = j;
Word.Shape shape = document.Shapes.get_Item(ref idx);
if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
{
Word.ContentControls contentControls = shape.TextFrame.TextRange.ContentControls;
for (int i = 1; i < contentControls.Count + 1; i++)
{
object objIdx = i;
ccArray.Add(contentControls.get_Item(ref objIdx));
}
}
}
return ccArray;
}

No comments:

Post a Comment

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.