Reputation: 45
I am trying to dynamically add bookmarks into a Word file from Excel based on the length of a dynamically allocated array. I then want to change the text at each bookmark to the corresponding value in the array.
My reason for doing this rather than just using static bookmarks is the program doesn't know how long the array will be or what data will be included until it runs. My thought process was to have one 'anchor' bookmark that the first iteration will use and then add bookmarks as needed after the original/previous one.
What I have below uses prevRange.End but it faults because this isn't a range, but I felt that it would get my point across as to what I was attempting to do.
I would use Bookmarks.InsertAfter except that I am trying to create a bullet list in Word and this messes with the formatting and reverses the order of the list.
I would prefer to find a way to dynamically do this rather than do a brute force method with a large amount of bookmarks and then delete 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
Upvotes: 4
Views: 4213
Reputation: 4518
You should be able to use the SetRange
method as per 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
Upvotes: 2