Dynamically create bookmarks with VBA

I am trying to dynamically add bookmarks to a Word file from Excel based on the length of a dynamically allocated array. Then I want to change the text in each bookmark to the corresponding value in the array.

My reason for this and not just using static bookmarks is that the program doesn't know how long the array will be or what data will be included before it runs. My thought process was to have one anchored bookmark that the first iteration would use, then add bookmarks as needed after the original / previous one.

What I have below uses prevRange.End, but it is wrong because it is not a range, but I felt it would make sense in regards to what I am trying to do.

I'd use Bookmarks.InsertAfter except I'm trying to create a list of letters in Word and it's a formatting mess and reverses the order of the list.

I would rather find a way to dynamically do this rather than using a brute force method with a lot of bookmarks and then deleting the ones I don't need.

wrdRange, prevRange, and wrdDoc are defined elsewhere in the program.

Dim Count As Integer
Dim CountM As Integer
Count = 1

Do While Clar(Count) <> ""       'Clar() is a dynamically allocated 1D array containing text
CountM = Count - 1
PrevBmarkName = "Clar" & CountM
BmarkName = "Clar" & Count      'Only bookmark in Word document to start with is Clar1
BmarkText = Clar(Count)

If Count <> 1 Then
    Set prevRange = wrdDoc.Bookmarks(PrevBmarkName).Range
    wrdDoc.Bookmarks.Add Name:="BmarkName", Range:=prevRange.End 'Faults here because prevRange.end isn't a range
    Set wrdRange = wrdDoc.Bookmarks(BmarkName).Range
    If Clar(Count + 1) = "" Then   'Used for the end of the list so there isn't a floating bullet point
        wrdRange.Text = BmarkText
        wrdDoc.Bookmarks.Add Name:=BmarkName, Range:=wrdRange
    Else
        wrdRange.Text = BmarkText & vbNewLine
        wrdDoc.Bookmarks.Add Name:=BmarkName, Range:=wrdRange
    End If
Else         'Functions normally through the first iteration, replaces Clar1 with clar(1) text
    Set wrdRange = wrdDoc.Bookmarks(BmarkName).Range
    wrdRange.Text = BmarkText & vbNewLine
    wrdDoc.Bookmarks.Add Name:=BmarkName, Range:=wrdRange
End If

Count = Count + 1
CountM = CountM + 1
Loop

      

+3


source to share


1 answer


You can use the method SetRange

as below:



    Set prevRange = wrdDoc.Bookmarks(PrevBmarkName).Range
    Set newRange = prevRange   'Have to set the range to something initially
    newRange.SetRange prevRange.End, prevRange.End
    ActiveDocument.Bookmarks.Add "BmarkName", newRange

      

+1


source







All Articles