Reputation: 31
I have a Word document that uses many different fields. I wrote a macro that updates all the sequence
, reference
, page, and numpages
fields in the document.
Updating text fields reverts them back to their default text so I don't want those updated.
This macro worked perfectly in Word 2007 but I recently updated to Word 2013 and it doesn't work properly anymore.
All page and numpages
fields are set to 1 when this macro runs. Yet when I update them manually, they update correctly.
Was there a change to how fields are updated in Office 2013?
The macro code is below.
Sub UpdateAllFields()
UnprotectDocument
'UpdateAllFields Macro
Dim objDoc As Document
Dim objFld As Field
'Updates the specified form fields. This can take a while when the document gets large
Set objDoc = ActiveDocument
For Each objFld In objDoc.Fields
If objFld.Type = wdFieldRef Then 'Updates Cross References
objFld.Update
If objFld.Type = wdFieldPage Then 'Updates Page Numbers
objFld.Update
ElseIf objFld.Type = wdFieldNumPages Then 'Updates Total Page Count
objFld.Update
ElseIf objFld.Type = wdFieldSequence Then 'Updates Sequence Fields
objFld.Update
End If
Next objFld
ProtectDocument
End Sub
Upvotes: 3
Views: 1955
Reputation: 11
It also happened to me that the page references all pointed to page 1 in the document when I used ActiveDocument.Fields.Update, but it worked when I updated them manually. After some trial and error I noticed that it worked using Selection.Fields.Update, so I modified the macro to the following:
Sub UpdateAllFields()
Dim oCurrentRng As Range
Dim oRng As Range
Application.ScreenUpdating = False
Set oCurrentRng = Selection.Range
Set oRng = ActiveDocument.Range
oRng.Select
Selection.Fields.Update
oCurrentRng.Select
Application.Screenupdating = True
End Sub
Hope that it helps someone!
//David
Upvotes: 1
Reputation: 2526
You should use SELECT instead of multiple IF ELSE as follow:
Sub UpdateAllFields()
UnprotectDocument
'UpdateAllFields Macro
Dim objDoc As Document
Dim objFld As Field
'Updates the specified form fields.
'This can take a while when the document gets large
Set objDoc = ActiveDocument
For Each objFld In objDoc.Fields
Select Case objFld.Type
Case wdFieldRef, wdFieldPage, wdFieldNumPages, wdFieldSequence
objFld.Update
End Select
Next objFld
ProtectDocument
End Sub
See, code is so clear and easy to understand.
Upvotes: 0