Vba обновление полей word

Thanks for these answers! I found the answers very good and learned some stuff about ms-word macros. I thought I’d make my own answer for consideration (and adding some more search engine keywords — my searches didn’t bring me here immediately).

I took inspiration from the citations in the footnotes.

I had an issue where MS Word fields were not updating in Textbox (Shapes).

I was working on a 70 page word document (Word 2013) that contained a lot of figures/images/captions and cross-references. A common practice is for an image to be captioned e.g. Figure 7, so it can be easily cross-referenced. Often the caption is inside a textbox (shape) and grouped with/to the object its captioning.

So after some document editing and content reorganisation, the fields and cross-references can easily get out of logical sequence.

OK — no problem… pressing CTRL+A then F9 to update the document fields should solve this?

Unfortunately that didn’t work as expected to update fields in textboxes (shapes).

In this scenario where fields exist inside textboxes (shapes) CTRL+A then F9 only updated the fields not inside a textbox (shape).

One can assume this behaviour is because field updating (F9) works on selected text, and with the CTRL+A then F9 approach only text outside of the textboxes (shapes) is selected, so the field update only applies outside of textboxes (shapes).

I’m surprised there is not a button on the ribbon to perform an «update all fields». There could even be a toggle option to prompt the user to update all fields when closing a document?

I checked Word’s (2013) ribbon command list, and didn’t find an Update All command.

enter image description here

Solution UpdateAllFields()

weeeeeee

Like the code shared by @Cindy here, the following code should update fields wherever they are in the doc, header, footer, main doc, textbox, grouped and nested grouped textbox.

Create a macro with the following code, and then add to the Quick Access Toolbar (QAT)

  1. Press ALT+F8 to open the Macros dialogue.
  2. Enter a name for the Macro: UpdateAllFields
  3. Press Create button
  4. Paste the code:
Sub UpdateAllFields()
    Application.ScreenUpdating = False
    With ActiveDocument
        .Fields.Update
        .PrintPreview
        .ClosePrintPreview
    End With
    Application.ScreenUpdating = True
End Sub

Finally add the Macro to the Quick Access Toolbar.

Citations and inspirations:

The Q&A’s in this post!

There is a related post on the Microsoft Community here: Word 365 Fields not updating in Textbox [serious reproducible error]. This suggests the issue is present in at least Word 2013 and Word 365.

There is a related post on Stack Overflow here: Macro to update fields in shapes (textboxes) in footer in Microsoft Word.

Another example UpdateTextboxFields()

This was the first version of code I wrote as I was in research and solution mode. Its a recursive approach to update fields inside textboxes, even if they are inside a group, or nested group. This doesn’t update fields outside shapes.

Public Sub UpdateTextboxFields()
    Application.ScreenUpdating = False
    With ActiveDocument
        Call IterateShapesCollection(.Shapes)
        .PrintPreview
        .ClosePrintPreview
    End With
    Application.ScreenUpdating = True
End Sub

Private Sub IterateShapesCollection(col)
    Dim shp As Shape
    For Each shp In col
        ' https://learn.microsoft.com/en-gb/office/vba/api/office.msoshapetype
        ' Ignore images and 
        If 1 = shp.Type Or 13 = shp.Type Then
            GoTo NextIteration
        End If
        
        'Debug.Print ("Name: " & shp.Name & ", Type: " & shp.Type)
        
        ' if the type is a group, recurse
        If 6 = shp.Type Then
            Call IterateShapesCollection(shp.GroupItems)
        Else
            Call UpdateShapeFields(shp)
        End If
        
NextIteration:
    Next
End Sub

Private Sub UpdateShapeFields(shp)
    With shp.TextFrame
        If .HasText Then
            .TextRange.Fields.Update
        End If
    End With
End Sub

Word display option: Update fields before printing

cite: Microsoft article Some fields are updated while other fields are not

The concept behind this option/approach is: all document fields are updated when you open print preview.

It looks like this option in Word (tested in 2013) updates all fields with a caveat — see below — you may need to open and close print preview twice.

File → Options → Display → Print options section → Update fields before printing

enter image description here

Caveat if the doc has cross-references to figures/captions

This caveat applies to the word «Update fields before printing» display option and the UpdateAllFields() macro.

IF the document contains cross-references to figures/captions (with numbers), and those figures/captions have changed sequence/place in the document…

You must update the fields twice, 1) to reflect the figures/captions update, and then 2) to update the cross-references.

In this article, you will find a VBA macro that lets you update all fields in a Word document no matter where the fields are found. The macro will find and update fields not only in the main body but also in headers, footers, footnotes, endnotes, text boxes and other shapes, etc. The macro will even find and update fields in shapes inside drawing canvases anywhere in the document.

You can install and use the macro without any knowledge about macros and VBA.

Macro updated 5-Aug-2020 (by mistake, some code lines were missing in the previous version).

What you should know about the update fields macro

The macro below will update all fields in the active Word document no matter where the fields are found. By using a macro to update fields, you simply need to run the macro to have all fields updated. Alternatively, you might have to perform a number of manual actions to make sure that all fields are updated if they are spread around in different parts of Word such as the main story, headers, footers, footnotes, endnotes, text boxes and other shapes.

Note that the macro includes a number of comments that explain a little about what is going on. The information after the macro code below will cover it in more detail.

You can copy the macro code below and insert it either in your Normal.dotm file or in another Word file of your choice. For help on installing a macro, see How to Install a Macro.

Warnings that may be shown if you manually update fields in Word are automatically suppressed when using the Update Fields macro

If you attempt to manually update fields in comments, footnotes and endnotes, Word may show a warning as illustrated in Figure 1 below, telling that the action cannot be undone. To allow the update fields macro to update all fields anywhere in the document without being stopped by such alerts, the macro code turns off such alerts while running.

Warning – update fields – can't undo action

Figure 1. Warning that may be shown in Word if you attempt to update fields in a comment, footnote or endnote. The update fields macro below suppresses such warnings.

Locked fields will not be updated by the macro

You can lock fields in Word. The purpose of locking fields is normally that you want to prevent the fields from being updated.

The macro below does not update locked fields. All locked fields will remain unchanged. It is, however, possible to create a macro that checks each individual field, unlocks it if locked, updates the field and locks it again.

For information about how to manually lock and unlock fields, see How to prevent fields from being updated – locked fields.

Protected documents must be unprotected before using the macro

If a document is protected, the purpose is normally to prevent any changes or certain changes to be made to the document. In case of a protected document, the macro shows a message (see Figure 2 below), telling you to unprotect the document before running the macro. Thereby, it is up to you to decide whether it is OK to update fields in the document.

The message that will be shown if you attempt to update all fields in a protected document

Figure 2. This message will be shown if you attempt to update all fields in a protected document.

Track changes and updating fields – the Update Fields macro lets you turn it off during the update

If you manually update fields in a Word document while track changes is turned on, every updated field will be marked as revisions where the old field is deleted and a new one added. This is most often just disturbing noise in the document. The macro below checks whether track changes is on. If that is the case, the macro shows the message in Figure 3, letting you turn it off during the field update. If you do so, track changes will be turned on again before the macro finishes.

Illustration of message that will be shown if track changes is turned on in the document in which you attempt to update all fields

Figure 3. This message will be shown if track changes is turned on in the document in which you attempt to update all fields.

It is possible to extend the macro with code that turns off any protection, updates the fields and finally sets the protection back to the original.

The code in the macro that updates fields in text boxes, shapes, etc. is found twice. That code could be moved to a function that is called from the main macro. That way, it would be needed only once. However, I decided to allow the redundant code so that only one sub is needed, making it simpler for users who are new to VBA.

The macro – UpdateAllFieldsInDocument

Sub UpdateAllFieldsInDocument()
    
'=========================
'Macro created 2019 by Lene Fredborg, DocTools - www.thedoctools.com
'Revised August 2020 by Lene Fredborg
'THIS MACRO IS COPYRIGHT. YOU ARE WELCOME TO USE THE MACRO BUT YOU MUST KEEP THE LINE ABOVE.
'YOU ARE NOT ALLOWED TO PUBLISH THE MACRO AS YOUR OWN, IN WHOLE OR IN PART.
'=========================
'The macro updates all fields in the activedocument no matter where the fields are found
'Includes fields in headers, footers, footnotes, endnotes, shapes, etc.
'=========================
    
    Dim oDoc As Document
    Dim rngStory As Range
    Dim oShape As Shape
    Dim oShape_2 As Shape
    Dim oTOC As TableOfContents
    Dim oTOF As TableOfFigures
    Dim oTOA As TableOfAuthorities
    Dim blnTurnOnTrackRevisions As Boolean

    On Error GoTo ErrorHandler
    
    If Documents.Count = 0 Then
        MsgBox "No documents are open.", vbOKOnly, "Update All Fields"
        Exit Sub
    Else
        Set oDoc = ActiveDocument
    End If

    With oDoc
        'Stop if document protection prevents full update of fields
        If .ProtectionType <> wdNoProtection Then
            MsgBox "The document is protected. In order to update all fields, you must first unprotect the document.", _
                vbOKOnly + vbInformation, "Update All Fields – Protected Document"
            GoTo ExitHere
        End If
        
        blnTurnOnTrackRevisions = False
        
        'Show msg if track changes is on
        'Let user turn it off to prevent all updated fields marked as revisions
        If .TrackRevisions = True Then
            If vbYes = MsgBox("Track changes is currently ON. Do you want to turn OFF track changes while updating fields?", _
                              vbYesNo + vbQuestion, "Turn Off Track Changes?") Then
                blnTurnOnTrackRevisions = True
                .TrackRevisions = False
            End If
        End If
    End With
    
    'Turn off screen updating for better performance
    Application.ScreenUpdating = False

    'Prevent alert when updating footnotes/endnotes/comments story
    Application.DisplayAlerts = wdAlertsNone

    'Iterate through all stories and update fields
    For Each rngStory In ActiveDocument.StoryRanges
        If Not rngStory Is Nothing Then
            'Update fields directly in story
            rngStory.Fields.Update
            
            If rngStory.StoryType <> wdMainTextStory Then
                'Update fields in shapes and drawing canvases with shapes
                For Each oShape In rngStory.ShapeRange
                    With oShape.TextFrame
                        If .HasText Then
                            .TextRange.Fields.Update
                        End If
                        
                        'In case of a drawing canvas
                        'May contain other shapes that may contain fields
                        If oShape.Type = msoCanvas Then
                            For Each oShape_2 In oShape.CanvasItems
                                With oShape_2.TextFrame
                                    If .HasText Then
                                        .TextRange.Fields.Update
                                    End If
                                End With
                            Next oShape_2
                        End If
                        
                    End With
                Next oShape
            End If

            'Handle e.g. multiple sections with unlinked headers/footers or linked text boxes
            If rngStory.StoryType <> wdMainTextStory Then
                While Not (rngStory.NextStoryRange Is Nothing)
                    Set rngStory = rngStory.NextStoryRange
                    rngStory.Fields.Update
                
                    'Update fields in shapes and drawing canvases with shapes
                    For Each oShape In rngStory.ShapeRange
                        With oShape.TextFrame
                            If .HasText Then
                                .TextRange.Fields.Update
                            End If
                            
                            'In case of a drawing canvas
                            'May contain other shapes that may contain fields
                            If oShape.Type = msoCanvas Then
                                For Each oShape_2 In oShape.CanvasItems
                                    With oShape_2.TextFrame
                                        If .HasText Then
                                            .TextRange.Fields.Update
                                        End If
                                    End With
                                Next oShape_2
                            End If
                            
                        End With
                    Next oShape
                Wend
            End If
        End If
    Next rngStory
    '=========================

    'Update any TOC, TOF, TOA
    For Each oTOC In oDoc.TablesOfContents
        oTOC.Update
    Next oTOC
    For Each oTOF In oDoc.TablesOfFigures
        oTOF.Update
    Next oTOF
    For Each oTOA In oDoc.TablesOfAuthorities
        oTOA.Update
    Next oTOA
    '=========================

ExitHere:
    On Error Resume Next
    'Restore to original track revisions if relevant
    If blnTurnOnTrackRevisions = True Then
        oDoc.TrackRevisions = True
    End If
    'Clean up
    Set oDoc = Nothing
    Set rngStory = Nothing
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = wdAlertsAll

    Exit Sub
    '=========================
ErrorHandler:
    'Make sure to display alerts again in case of an error
    Resume ExitHere
End Sub

Related information

You will find a number of other articles on this website related to macros and fields.

For help on installing a macro, see How to Install a Macro.

For detailed information about how Word updates fields, see my article Updating Fields in Word – How it Works.

For an overview of keyboards shortcuts related to fields, see my article about useful shortcuts related to fields.

For information about DocProperty fields, see my article How properties and DocProperty fields work on my website wordaddins.com

For details about cross-reference fields, see my article How cross-reference fields in Word work on my website wordaddins.com.

In case of problems with cross-reference fields not being updated as expected, see my article Cross-reference Problems — Troubleshooting.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Fields.Update method (Word)

vbawd10.chm154140773

vbawd10.chm154140773

word

Word.Fields.Update

55aaae86-015f-fc4f-ff7c-42fddad05c27

06/08/2017

medium

Fields.Update method (Word)

Updates the result of the fields object.

Syntax

expression.Update

expression Required. A variable that represents a ‘Fields’ collection.

Return value

Long

Remarks

Returns 0 (zero) if no errors occur when the fields are updated, or returns a Long that represents the index of the first field that contains an error.

Remark: When using this with Word 2016 and possibly with others, the number may be incorrect.

Example

This example updates all the fields in the main story (that is, the main body) of the active document. A return value of 0 (zero) indicates that the fields were updated without error.

If ActiveDocument.Fields.Update = 0 Then 
 MsgBox "Update Successful" 
Else 
 MsgBox "Field " & ActiveDocument.Fields.Update & _ 
 " has an error" 
End If

See also

Fields Collection Object

[!includeSupport and feedback]

Студворк — интернет-сервис помощи студентам

Добрый день!

Прошу подсказать, как можно обновить поле типа (DocProperty) вставленное в фигуру, если фигура находится в составе группы (сгруппированный объект/фигура)?
Файл шаблона приложен

Опробованные варианты
1) Обновление поля через PrintPreview. Не подходит. У многих в настройках отключено обновление полей при печати

Visual Basic
1
2
3
4
5
6
Sub UpdateAllFields()
  Application.ScreenUpdating = False 'Отключение обновления экрана
  ActiveDocument.PrintPreview 'Предварительный просмотр
  ActiveDocument.ClosePrintPreview 'Закрыть предварительный просмотр
  Application.ScreenUpdating = True 'Обновить экран
End Sub

2) Макрос взят Отсюда. Не обновляет поля вставленные в TextFrame

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Sub uHeadersFooters()
'Обновление всех полей в колонтитулах активного документа во всех разделах
Dim oSection As Section
Dim HF As HeaderFooter
For Each oSection In ActiveDocument.Sections
   For Each HF In oSection.Headers
      HF.Range.Fields.Update
   Next HF
Next oSection
For Each oSection In ActiveDocument.Sections
   For Each HF In oSection.Footers
      HF.Range.Fields.Update
   Next HF
Next oSection
End Sub

3) Макрос взят Отсюда. Не обновляет поля в сгруппированных объектах

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Public Sub UpdateAllFields()
  Dim rngStory As Word.Range
  Dim lngJunk As Long
  Dim oShp As Shape
  lngJunk = ActiveDocument.Sections(1).Headers(1).Range.StoryType
  For Each rngStory In ActiveDocument.StoryRanges
    'Iterate through all linked stories
    Do
      On Error Resume Next
      rngStory.Fields.Update
      Select Case rngStory.StoryType
        Case 6, 7, 8, 9, 10, 11
          If rngStory.ShapeRange.Count > 0 Then
            For Each oShp In rngStory.ShapeRange
              If oShp.TextFrame.HasText Then
                oShp.TextFrame.TextRange.Fields.Update
              End If
            Next
          End If
        Case Else
          'Do Nothing
        End Select
        On Error GoTo 0
        'Get next linked story (if any)
        Set rngStory = rngStory.NextStoryRange
      Loop Until rngStory Is Nothing
    Next
End Sub

Fields that don’t update automatically pose a problem with many users because they don’t remember to update them manually. When you need this functionality, use this VBA procedure.

Image: insjoy, Getty Images/iStockPhoto

The article How to update a page number reference in a Word document uses fields to update cross-references in a Microsoft Word document. The problem is that the fields in use won’t update automatically, so the user must remember to do so. That’s not ideal because it’s a task that’s easy to forget. In this article, I’ll show you a built-in setting that updates the fields before printing, and then I’ll show you a VBA solution.

SEE: 83 Excel tips every user should master (TechRepublic)

I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. Word Online won’t support the solutions in this article. For quick access to the VBA code, you can download the demonstration .docm, .doc and .cls files.

How to update when printing in Word

To update an individual field, click on it and press F9 or right-click and select Update Field. To update all references in a document, press Ctrl + A, then press F9. Even if you only have one or a few, it’s hard to remember to manually update those fields. Instead, you can set Word to always update fields before printing your document as follows:

  1. Click the File menu and choose Options or More and then Options in the left pane.
  2. Choose Display in the left pane.
  3. In the Printing section, check the Update Fields Before Printing option (Figure A).
  4. Click OK.

Figure A

As you might suspect, this option is limited. First, if you’re sending the document by email you won’t be printing, so this option is useless. In addition, you might not notice that a field doesn’t update if a bookmark or reference is broken because you won’t be viewing the document before updating when printing.

This option has its place, but let’s look at a code solution that’s more dependable.

How to update with VBA in Word

The VBA command to update fields

ThisDocument.Fields.Update

is easy to implement. Listing A shows how easy it is to update all fields when closing a document.

Listing A

Private Sub Document_Close()

‘Update all fields when closing document.

ThisDocument.Fields.Update

End Sub

This procedure uses the Document object’s Close event. That means, closing the document triggers the event that updates all fields. It’s slick and easy. The only real problem is deciding what event to use, and Close makes the most sense to me. You can use the Open event, but that won’t update fields after you modify the document.

You could trigger both the Open and Close events to cover most situations. In addition, check the option reviewed at the beginning of this article to cover almost every possible scenario:

  • If the user prints the document, the fields are updated first.
  • If the user makes modifications and closes the document before emailing, the fields are updated first.
  • If the user opens the document and prints without making modifications, the fields are updated first.

There is one possibility that isn’t covered: The user opens the file, makes modifications, and then sends the file without closing the document, which isn’t likely because most of us would close and save the document before sending it.

SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)

I’ve added the procedure in Listing A to the downloadable files. I’m using the demonstration files used in the linked article in the introduction. You can work with any Word document, but you’ll want to add a field that doesn’t update automatically to the body of the document. There are three pages. On page 2 is a text reference. On page 3, a cross-reference field returns the page number of the text reference on page 2. If you enter a page between pages 1 and 2, the text reference moves to page 3 and the cross-reference moves to page 4. However, the cross-reference will still return page 2 because it won’t update automatically.

If you decide to enter the procedure manually, be sure to save the workbook as a macro-enabled file if you’re using a ribbon version or the procedure won’t run. If you’re using a menu version, you can skip this step. To add the procedure, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, select ThisDocument. You can enter the code manually or import the downloadable .cls file. In addition, the procedure is in the downloadable .docm and .doc files. If you enter the code manually, don’t paste from this web page. Instead, copy the code into a text editor and then paste that code into the ThisDocument module. Doing so will remove any phantom web characters that might otherwise cause errors.

To use the procedure simply close your document. But first, if you’re using a demonstration file, add a page to the demonstration .docm or .doc file between pages 1 and page 2 to move the text reference on page 2 to page 3. The cross-reference field that was on page 3 is now on page 4, but it won’t update automatically. When prompted to save when you close the file, click Save. When you reopen the document, any field that needs to be updated will display the correct result. To learn more about this demonstration file’s fields and its purpose, read the linked article in the introduction.

If you find this a bit too confusing, you don’t need to use the demonstration file. You can try this with any Word document that contains fields that don’t update automatically.

This simple procedure has one limitation, which doesn’t impact our specific example: It updates fields only in the main story of the document. It won’t update fields in headers, footers, footnotes or endnotes. That’s not an issue for us because Word would update the {PageRef} field (the field we’re using) if it were in the header or footer.

The procedure in Listing A is a good place to start, but as mentioned it has limitations. In a future article, I’ll show you how to usurp the Save command to update fields when you save the file. In addition, you can look forward to an article that updates fields beyond the main story.

Like this post? Please share to your friends:
  • Vba нечеткий поиск excel
  • Vba несколько книг excel в одну
  • Vba не работает excel только
  • Vba не переходит к word
  • Vba не могу открыть книгу excel