So, I'm trying to use an excel spreadsheet to populate a word template. The named ranges in the.xlsm file are the same as the word template bookmark names. Most run just fine, but for two of them, the.bookmarks.add method fails without an error or warning and the bookmark is then lost. As far as I can see, there is nothing special or particular about these two. What might be the cause?
The offending bookmarks are called "client_address2" (of 2) and "test_name2" (of 3).
Sub preencher_word_2dd()
'Substitui os bookmarks do word pelo conteúdo do Bookmarks.xlsm
Dim wdApp As Word.Application
Dim wDoc As Word.Document
Dim bmkwb As Workbook
Dim bmk As Worksheet
Dim nome_report As String
Dim i As Integer
Set bmkwb = ActiveWorkbook
Set bmk = bmkwb.Sheets(1)
'Get the running word application
Set wApp = GetObject(, "Word.Application")
'get report name to be updated
nome_report = bmk.Range("project_number").Value & "_" & bmk.Range("report_number") & "_01 Overview.docx"
'select the correct, already open, word document
Set wDoc = wApp.Documents(nome_report)
Debug.Print wDoc.Bookmarks.Count
i = 1
With wDoc
For i = 1 To .Bookmarks.Count
For Each nm In bmkwb.Names
If .Bookmarks(i).Name = nm.Name Then
'On Error Resume Next
UpdateBookmark wDoc, .Bookmarks(i), nm.RefersToRange.Value
'On Error GoTo 0
Exit For
End If
Next nm
Next i
.Fields.Update
End With
Debug.Print wDoc.Bookmarks.Count
End Sub
Sub UpdateBookmark(wDoc As Word.Document, b As Word.Bookmark, TextToUse As String)
Dim BMRange As Word.Range
Dim BMName As String
Dim n_bmks As Integer
n_bmks = wDoc.Bookmarks.Count
Set BMRange = b.Range
BMName = b.Name
BMRange.Text = TextToUse
wDoc.Bookmarks.Add BMName, BMRange
If n_bmks <> wDoc.Bookmarks.Count Then
Debug.Print BMName, BMRange
Debug.Print wDoc.Bookmarks.Count, "Bookmark lost"
End If
End Sub
Thanks in advance!
You refer to bookmarks «called "client_address2" (of 2) and "test_name2" (of 3)». I assume these are named "client_address1", "client_address2", "test_name1", "test_name2", and "test_name3", as Word documents cannot have two or more bookmarks with the same name.
Are any bookmarks contained within or overlapping another bookmark? if so, that might result in your 'For i = 1 To.Bookmarks.Count' crashing out if those embedded/overlapping bookmarks longer exist. As for:
i = 1
With wDoc
For i = 1 To .Bookmarks.Count
For Each nm In bmkwb.Names
If .Bookmarks(i).Name = nm.Name Then
'On Error Resume Next
UpdateBookmark wDoc, .Bookmarks(i), nm.RefersToRange.Value
'On Error GoTo 0
Exit For
End If
Next nm
Next i
.Fields.Update
End With
that could all be reduced to:
With wDoc
For Each nm In bmkwb.Names
If .Bookmarks.Exists(nm.Name).Name Then _
Call UpdateBookmark(wDoc, .Bookmarks(nm.Name), nm.RefersToRange.Value)
Next nm
.Fields.Update
End With
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.