删除PowerPoint幻灯片的所有形状

时间:2014-04-02 12:30:16

标签: .net c#-4.0 powerpoint powerpoint-vba powerpoint-2010

我尝试使用以下代码删除所有形状:


PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.Presentation ppP = ppApp.ActivePresentation;
PowerPoint.Slide ppS = ppApp.ActiveWindow.Selection.SlideRange[1];
PowerPoint.Shapes shapes = ppS.Shapes;

foreach (PowerPoint.Shape shape in shapes)
{
      shape.Delete(shape);                    
}

它不能像我预期的那样删除所有形状,因为删除形状时会影响PowerPoint.Shapes。如果我想删除所有形状,我需要将所有形状添加到List中,然后删除每个形状,如:


PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.Presentation ppP = ppApp.ActivePresentation;
PowerPoint.Slide ppS = ppApp.ActiveWindow.Selection.SlideRange[1];
PowerPoint.Shapes shapes = ppS.Shapes;
if (shapes == null) return;

List listShapes = new List();
foreach (PowerPoint.Shape shape in shapes)
{
      listShapes.Add(shape);                    
}

foreach (PowerPoint.Shape shape in listShapes)
{
      shape.Delete();
}

还有其他方法可以更快地删除吗?

1 个答案:

答案 0 :(得分:1)

您无法迭代集合并从该集合中删除项目,因为这会影响集合。所以试着避免for-each循环:

while (shapes.Count > 0) {
  shapes[0].Delete();
}

不是100%确定与PowerPoint有关的语法,但这是一般的想法。

相关问题