I generated the VBA code below in order to populate a large Word template document from Excel. My goal is to update a bookmark and then the associated cross references to that bookmark to update as well while the template controls different styles of the same text.
What I'm encountering is that the bookmark is just replaced with text, the bookmark itself disappears, and therefore the cross references do not update through the document. My working knowledge of VBA in Excel is limited.
Sub exportToWord()
Dim WordApp As Word.Application
Dim doc As Word.Document
Dim expoDoc As Word.Document
Dim rng_project_name As Word.Range
Dim docPath As String, expoPath As String
Dim bookmark As Word.bookmark
On Error Resume Next ' Enable error handling
' Specify the output path for the Word document
expoPath = Range("outputPath").Value & Range("project_name").Value & ".docx"
' Create a new instance of Word Application
Set WordApp = New Word.Application
If WordApp Is Nothing Then
MsgBox "Word is not installed or an error occurred."
Exit Sub
End If
WordApp.Visible = False
' Open the existing Word document
Set doc = WordApp.Documents.Open([wordPath].Text)
If doc Is Nothing Then
MsgBox "The specified document could not be opened."
WordApp.Quit
Set WordApp = Nothing
Exit Sub
End If
' Update all bookmarks in the document
For Each bookmark In doc.Bookmarks
If Not bookmark.Range Is Nothing Then
If bookmark.Name = "project_name" Then
bookmark.Range.Text = Range("project_name").Value
' Add code here for other bookmarks if needed
End If
End If
Next bookmark
' Save the modified content to a new temporary Word document
doc.SaveAs2 expoPath, Word.WdSaveFormat.wdFormatDocumentDefault
doc.Close ' Close the original document
' Open the temporary document to work with it
Set expoDoc = WordApp.Documents.Open(expoPath)
If expoDoc Is Nothing Then
MsgBox "The temporary document could not be opened."
WordApp.Quit
Set WordApp = Nothing
Exit Sub
End If
' Clean up the objects and close the Word application
Set doc = Nothing
WordApp.Quit
Set WordApp = Nothing
On Error GoTo 0 ' Reset error handling
End Sub```
bookmark.Range.Text = ..
will remove bookmark