MS Word 2013 crash when objects are generated / deleted

388 views Asked by At

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?

1

There are 1 answers

3
Kazimierz Jawor On

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:

For i=arrShapes.Count to 1 step -1
   'you dont need if statement here
   tl = Left(arrShapes.Item(i).Title, 1)
   if tl = "A" then
    tl = Mid(arrShapes.Item(i).Title, 2, Len(arrShapes.Item(i).Title) - 2)
    'rather dont' need it any more: nr = Int(tl)
    arrShapes.Item(i).Delete
    'rather dont' need it any more: Set arrShapes(nr) = Nothing
   end if
Next i

Not tested! Some adjustment can be required as not everything is clear in your code.