简体   繁体   中英

How does a for cycle loops trough items, if you delete and add one item mid-loop?

I've wondered about this, on word 2007 this didn't work as I expected, and on word 2016 it did. Let-me explain:

I have a for loop

For i = ActiveDocument.Sections(1).Headers(1).Shapes.count To 1 Step -1

 if  ActiveDocument.Sections(1).Headers(1).Shapes(i) matches condition, then

ActiveDocument.Sections(1).Headers(1).Shapes(i).delete
set newshape = ActiveDocument.Sections(1).Headers(1).Shapes.Addpicture(new picture, bla, bla, bla..)

end if
next i

In this circumstance, will the loop encounter the newly added shape, and cycle trough it? Or will it ignore it?

To manage this issue I tough of setting ActiveDocument.Sections(1).Headers(1).Shapes(i) as an object, and delete it inside the loop, after inserting the new one.

  • But what if I just set the one I want to delete invisible instead? Will the one inserted, be processed in the loop?

I also considered making a collection of all the shapes I wanted to delete, and then loop inside the collection to delete and add new shapes, in order to make sure he wouldn't loop trough a shape inserted in the middle of it.

Thanks for any insights on this question

In addition to what Cindy said, your code would be more efficient and easier to follow as:

With ActiveDocument.Sections(1).Headers(1)
  For i = .Shapes.Count To 1 Step -1
    If .Shapes(i) matches condition Then
      .Shapes(i).Delete
      Set newshape = .Shapes.AddPicture(new picture, bla, bla, bla)
    End If
  Next i
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM