0

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?

JNYRanger
  • 6,829
  • 12
  • 53
  • 81
Crumboo
  • 25
  • 5

1 Answers1

1

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...

haraman
  • 2,744
  • 2
  • 27
  • 50
  • 1
    Perfect, that worked (with the only change that the loop ends at 1 instead of 0 - oDoc.Bookmarks(0) doesn't exist apparently). Thank you! – Crumboo Oct 21 '15 at 06:10
  • That would depend on the collection type, whether it is zero based or not. Such as a collection of 5 items can be iterated *0 to 4 if it is zero based* and 1 to 5 if it is not and vice-versa – haraman Oct 21 '15 at 06:20