Updating page numbers in VBA
I have a Word document that uses many different fields. I wrote a macro that updates all fields , pages, and . sequence
reference
numpages
Updating the textboxes brings them back to the default text, so I don't want those to be updated.
This macro worked fine in Word 2007, but I recently upgraded to Word 2013 and it doesn't work anymore.
All pages and margins are set to 1 when this macro is executed. However, by manually updating them, they update correctly. numpages
Has the field change been changed in Office 2013?
Macros are shown 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
source to share
I also happened to have the page links link to page 1 in the document when I used ActiveDocument.Fields.Update, but it worked when I manually updated them. After some trial and error, I noticed that it was working using Selection.Fields.Update, so I changed the macro to this:
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 this helps someone!
//David
source to share
You should use SELECT instead of multiple IF ELSEs as shown 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
Select Case objFld.Type
Case wdFieldRef, wdFieldPage, wdFieldNumPages, wdFieldSequence
objFld.Update
End Select
Next objFld
ProtectDocument
End Sub
See, the code is so clear and straightforward.
source to share