Search code examples
c#vstoword-interop

How to go through the items in a msoGroup shape in a MSWord document?


I am writing a VSTO for Word 2010. I want to exam the shapes in a msoGroup shape but failed to get the shapes in the group. Here are my tries:

public void TestGroupShapes_Action(Microsoft.Office.Core.IRibbonControl control)
{
    Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;

    foreach(Microsoft.Office.Interop.Word.Shape shape in doc.Shapes)
    {
        if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoGroup)
        {
            /*
            // System.InvalidCastException:
            // Cannot convert System.__ComObject to Microsoft.Office.Interop.Word.Shape”
            foreach (Shape groupShape in shape.GroupItems)
            {
                Console.WriteLine(groupShape.Name);
            }
            */

            for(int i=0; i<shape.GroupItems.Count; i++)
            {
                // System.ArgumentException: Cannot use the index in the assembly.
                Microsoft.Office.Interop.Word.Shape groupShape = shape.GroupItems[i];
                Console.WriteLine(groupShape.Name);
            }
        }
    }
}

How to solve the problem?


Solution

  • GroupItems's first item starts at index 1 and not 0. Thats the reason you are getting

    System.ArgumentException: Cannot use the index in the assembly

    exception.

    In order to iterate trough the collection use the following code:

    for (int i = 1; i <= shape.GroupItems.Count; i++)
    {                       
        Microsoft.Office.Interop.Word.Shape groupShape = shape.GroupItems[i];
        
        // do something
    }