VBA crashes when trying to insert a multitude of CrossReferences

Viewed 100

I encountered a mysterious problem when trying to run the following thing in VBA for Word:

Option Explicit

Sub Test()
    Dim allHeadlines As Variant
    Dim i As Integer

    allHeadlines = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)  ' Gets all headlines

    For i = 1 To UBound(allHeadlines)
        Selection.InsertCrossReference ReferenceType:="Nummeriertes Element", _
        ReferenceKind:=wdNumberRelativeContext, ReferenceItem:=Str(i), _
        InsertAsHyperlink:=True, IncludePosition:=False, SeparateNumbers:=False, _
        SeparatorString:=" "
    Next
End Sub

The idea was simple: Just get all headlines and write them down automatically. (Actually, my intention was a bit different, but I broke the program down as much as I could.) "Nummeriertes Element" means "numbered element".

After 296 elements, the program crashes with a very unspecific error (Runtime Error '4198': "Command Failed") at the Selection.InsertCrossReference command. If I ignore the error and try to move on, Word crashes with an equally unspecific "heap damaged" error.

What also bothers me is that if I restart the Sub, it will fail immediately with Runtime Error '4198'. I have to restart Word completely to be able to run the Sub again, and then it will again crash at the same point (296 elements). Seems like some buffer is full and will not be cleared until I restart Word, but this is very annoying (I have much more than 300 headlines in this document).

I am quite at a loss here, because I do not really understand what is going on, or how to circumvent the problem. Does somebody else have an idea what is going on or what I am doing wrong?

1 Answers
Related