I am using Excel VBA to populate bookmarks in Word. I also want to update a bookmark in the footer of the document. Whenever the bookmark is not in the footer, my code works fine. However, when the bookmark in the footer should be populated, I get a Run-time error '5678' Word cannot find the requested bookmark.
.
I tried recording the code in Word, which gives me the following:
Selection.Goto What:=wdGoToBookmark, Name:=Bookmarkname
Since I am working from Excel I have changed this code to, where wordobject = CreateObject("Word.Application")
:
wordobject.Selection.Goto What:=wdGoToBookmark, Name:=Bookmarkname
As stated above, this code works fine when the bookmark is in the 'normal' text. Whenever the bookmark is in the footer, it throws the error.
How can I populate bookmarks in the footer of the Word-document?
Your code would probably works, if you manually select all the footer and run it.
However, you are probably not keen on such a solution. In general, using Selection
in VBA always causes problems sooner or later. Thus, make a favour to your future self and consider avoiding it. How to avoid using Select in Excel VBA
This is how to change the Text of any bookmark in Word, including those on the footers and the headers (works from Word only):
Option Explicit
Sub TestMe()
Dim bmk As Bookmark
For Each bmk In ThisDocument.Bookmarks
If bmk.Name = "wdGoToBookmark" Then
bmk.Range.Text = "Something new here"
End If
Next bmk
End Sub
In general, to see info for the bookmarks in the immediate window, a standard loop can help (works from Word only):
Sub TestMe()
Dim bmk As Bookmark
For Each bmk In ThisDocument.Bookmarks
Debug.Print bmk.Name
Debug.Print bmk.Range.Text
Next bmk
End Sub
If you want to make it work from Excel, then you cannot define variables as bookmarks in Excel. But something like this will do the job:
Public Sub TestMe()
Dim wordObj As Object
Dim wordObjD As Object
Dim bmk As Object
Dim countBmks As Long
Set wordObj = CreateObject("Word.Application")
Set wordObjD = wordObj.documents.Add("K:\yourPath\yourFile.docx")
wordObj.Visible = True
'Check whether a bookmark exists (FYI):
Debug.Print wordObjD.bookmarks.exists("someBookmark")
For Each bmk In wordObjD.Bookmarks
Debug.Print bmk.Name
Debug.Print bmk.Range.Text
If bmk.Name = "TheNameOfTheBookmark" Then
bmk.Range.Text = "SomeText"
End If
Next bmk
End Sub