I'm using Word 2013 to generate some objects and also delete them before a new generation. But sometimes Word crashes in such case, that all the VBA code is dropped. Here is the code for adding the generated objects:
For i = 1 To nodes
Set arrShapes(j) = docNew.Shapes.AddShape(MsoAutoShapeType.msoShapeDiamond, arrRawPoints(i, 1) - 2, arrRawPoints(i, 2) - 2, 4, 4)
arrShapes(j).title = "A" + Str(j) + "d"
arrShapes(j).Fill.ForeColor.RGB = RGB(255, 0, 0)
j = j + 1
Next i
The deleting code is as follows:
For Each sp In arrShapes
If Not (sp Is Nothing or IsEmpty(sp)) Then
tl = Left(sp.title, 1)
If tl = "A" Then
tl = Mid(sp.title, 2, Len(sp.title) - 2)
nr = Int(tl)
sp.Delete
Set arrShapes(nr) = Nothing
End If
End If
Next sp
Sometimes there occurs a crash, but if I call this routine 50 times or more, it runs perfectly. It happens that a user deletes such a generated object by hand, then I've got a crash. To find the reason, I've set a breakpoint on the 1st line within the For Each loop, but then Word crashes every time. What's wrong in this concept?
I think solution is quite obvious- when deleting you need to loop from last item to first therefore you need to switch into different kind of loop. Your (second) code could looks as follows:
Not tested! Some adjustment can be required as not everything is clear in your code.