The regular 'update all fields' method in Word does not update used fields in the headers and footers. I searched on the internet to find a proper method and I found some code, but almost every time, they didn't really do what they are supposed to do. I found one piece of code which will update the fields in headers and footers. I combined it with the normal update procedure and now I have one method to update all field:
Public Sub UpdateAllFields()
Dim currentDocument As Document _
= Globals.DnmOfficeAddIn.Application.ActiveDocument
If currentDocument IsNot Nothing Then
Dim aStory As Range
Dim NumberOfFields As Integer = 0
Cursor.Current = Cursors.WaitCursor
Try
For Each aStory In currentDocument.StoryRanges
NumberOfFields += aStory.Fields.Count
Next
If NumberOfFields > 0 Then
'Update all available fields in the document
For Each aStory In currentDocument.StoryRanges
aStory.Fields.Update()
Next
Dim section As Section
Dim DocumentRange As Range
Dim DocumentHeaderFooter As HeaderFooter
' Loop through the header/footer for each section.
' If this isn't done specifically, Word seems to
' skip the header/footer of sections after section 1.
For Each section In currentDocument.Sections
For Each DocumentHeaderFooter In section.Headers
DocumentRange = DocumentHeaderFooter.Range
For Each aField As Field In DocumentRange.Fields
If aField.Type = WdFieldType.wdFieldDocProperty Then
aField.Update()
End If
Next aField
Next DocumentHeaderFooter
For Each DocumentHeaderFooter In section.Footers
DocumentRange = DocumentHeaderFooter.Range
For Each aField As Field In DocumentRange.Fields
If aField.Type = WdFieldType.wdFieldDocProperty Then
aField.Update()
End If
Next aField
Next DocumentHeaderFooter
Next section
Else
MessageBox.Show( _
"This document does not contain any updatable fields.", _
"No fields", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End If
Finally
Cursor.Current = Cursors.Default
End Try
End If
End Sub
Good luck!
(By the way, I used this code in a Office 2007 environment)
EDIT: See my latest blog for a working version: http://blog.vanmeeuwen-online.nl/2009/09/update-all-fields-in-word-including.html
6 comments:
this did not work at all in word 2007. but this did work well even in text boxes:]
http://gregmaxey.mvps.org/Field_Macros.htm
Hi Hardijs,
Well, in my environment (Office 2007 on Win XP Pro), it works fine.
Dude! How come your comments work?!!
I used the same blog layout but my "Post comments" didn't work? How'd you do it? Please help me! T_T
It's an option you can switch on and off. Go to the settings menu and select the sub menu 'comments'. There you can select 'Show'
THANK YOU THANK YOU THANK YOU! You have made it clear and I am grateful.
Post a Comment