如何浏览 MSWord 文档中 msoGroup 形状中的项目?

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

我正在为 Word 2010 编写 VSTO。我想检查 msoGroup 形状中的形状,但无法获取组中的形状。这是我的尝试:

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);
            }
        }
    }
}

如何解决问题?

GroupItems 的第一项从索引 1 而不是 0 开始。这就是你得到

的原因

System.ArgumentException: Cannot use the index in the assembly

异常。

为了遍历集合,请使用以下代码:

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