Crumboo
Crumboo

Reputation: 25

Iterate bookmarks collection in for each loop

I have this problem with a loop for filling text into bookmarks in a MS Word document. It seems that the loop keeps restarting everytime and never gets to the 'next' bookmark.

Here is the code (the reason I use the .StartsWith is that I have several bookmarks that need to be filled with the same text):

For Each bm As Word.Bookmark In oDoc.Bookmarks
    Select Case True
        Case bm.Name.StartsWith("A")
            Call UpdateBookmarks(oDoc, bm.Name, TextA)
        Case bm.Name.StartsWith("B")
            Call UpdateBookmarks(oDoc, bm.Name, TextB)
        Case bm.Name.StartsWith("C")
            Call UpdateBookmarks(oDoc, bm.Name, TextC)
            'etc...
    End Select
Next

As said, the loop keeps restarting on the first bm in the Collection. If I do:

For Each bm As Word.Bookmark In oDoc.Bookmarks
    MsgBox(bm.Name)                    
Next

The loop works as it should (I get the bookmark names for all the bookmarks). The called sub looks like this:

Public Sub UpdateBookmarks(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByVal BookmarkName As String, ByVal Text As String)
    Dim BMrange As Word.Range = Doc.Application.ActiveDocument.Bookmarks(BookmarkName).Range
    BMrange.Text = Text
    Doc.Application.ActiveDocument.Bookmarks.Add(Name:=BookmarkName, Range:=BMrange)
End Sub

Any ideas why the first loop isn't working properly?

Upvotes: 0

Views: 1662

Answers (1)

haraman
haraman

Reputation: 2752

I have never played with the word, document, bookmark things but as per my understanding, bookmark is an enumerable collection and modifying it in the loop by its member may be causing the problem. In simple words just try to iterate over the index such as

For intI As Integer = oDoc.Bookmarks.Count - 1 To 0 Step -1
    Dim stName As String = ""
    stName = oDoc.Bookmarks(intI).Name
    Select Case stName.Substring(0, 1)
        Case "A"
            Call UpdateBookmarks(oDoc, stName, TextA)
        Case "B"
            Call UpdateBookmarks(oDoc, stName, TextB)
        Case "C"
            Call UpdateBookmarks(oDoc, stName, TextC)
            'etc...
    End Select
Next

I have iterated the loop in reverse order so that deletion of any item in the collection should not cause any exception like Index out of...

Upvotes: 1

Related Questions