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.

Ваши документы могут содержать различные поля: перекрестные ссылки, оглавления, предметные указатели, нумерацию, даты и т.д., некоторые из которых нуждаются в периодическом обновлении. Например, добавлены или изменились названия глав, которые присутствуют в оглавлении, рисунки были перенесены, удалены или добавлены новые и так далее. После этих действий необходимо принудительно обновлять поля.

Однако редактор Word не имеет стандартных возможностей обновления всех полей в документе одновременно и без лишних мышедвижений (если не считать использование сочетаний клавиш для выделения всего текста — «Ctrl+A» и последующего обновления с помощью клавиши «F9»).

Тем не менее, есть решение: можно воспользоваться специальным макросом, который будет автоматически обновлять все ваши поля при каждом открытии документа.

Для этого разместите приведенный ниже код макроса в ваш шаблон Normal.dot (Normal.dotm), на основе которого вы создаете свои документы, или в конкретный документ (P.S.: макрос обновлен 27.03.2008, так как Оглавление в документе не обновлялось, если это не сделать явным образом).

Sub AutoOpen()
'Автообновление всех полей документа при его открытии
Dim aStory As Range
Dim aField As Field
Dim myTOC As TableOfContents
For Each aStory In ActiveDocument.StoryRanges
  For Each aField In aStory.Fields
    aField.Update
  Next aField
Next aStory
For Each myTOC In ActiveDocument.TablesOfContents
   myTOC.Update
Next myTOC
End Sub

Если вы желаете обновлять поля вручную, то измените наименование макроса, создайте для него кнопку и разместите ее на панели инструментов (для Word 2003) или на панели быстрого доступа (для Word 2007).

Если вы не знаете, как подключить к документу и применить этот макрос, изучите следующие заметки с сайта:

Создание макроса из готового кода

Автоматическая запись макроса

Иногда требуется вручную обновить информацию в определенных полях, например, используемых в оглавлениях, колонтитулах, перекрестных ссылках, закладках и формулах в таблицах. Вы можете обновить поля по очереди или одновременно во всем документе.

Обновление поля

В открытом документе щелкните правой кнопкой мышки поле, например, оглавление, номер страницы или перекрестную ссылку, а затем выберите команду Обновить поле.

Если вы обновляете оглавление, в диалоговом окне Обновление оглавления укажите, хотите вы обновить только номера страниц или всю таблицу. В первом случае обновится только нумерация страниц для существующих разделов. Новые разделы при этом не добавятся в оглавление. Чтобы учесть новые разделы, установите переключатель обновить целиком.

Если у вас возникли затруднения при поиске полей в тексте, можно отобразить все поля на сером фоне. Для этого откройте меню Файл > Параметры > Дополнительно, а затем в разделе Показывать содержимое документа в раскрывающемся меню Затенение полей выберите пункт Всегда.

Обновление всех полей в документе

Нажмите клавиши CTRL+A.

Нажмите клавишу F9.

Если в документе содержатся таблицы с полями или формулами, может потребоваться выбрать каждую из них отдельно, а затем нажать клавишу F9.

Совет: Чтобы не забыть обновить оглавление перед печатью документа, настройте Word для автоматического обновления полей перед печатью. Откройте меню Файл > Параметры > Экран, а затем в разделе Параметры печати, установите флажок Обновлять поля перед печатью.

Примечание: При обновлении поля могут возникнуть проблемы, если элемент, на который оно ссылается, удален. Ссылки и закладки также могут указывать на несуществующие страницы. Дополнительные сведения см. в статье Устранение неполадок с закладками.

Ваши документы могут содержать различные поля: перекрестные ссылки, оглавления, предметные указатели, нумерацию, даты и т.д., некоторые из которых нуждаются в периодическом обновлении. Например, добавлены или изменились названия глав, которые присутствуют в оглавлении, рисунки были перенесены, удалены или добавлены новые и так далее. После этих действий необходимо принудительно обновлять поля.

Однако редактор Word не имеет стандартных возможностей обновления всех полей в документе одновременно и без лишних мышедвижений (если не считать использование сочетаний клавиш для выделения всего текста — «Ctrl+A» и последующего обновления с помощью клавиши «F9»).

Тем не менее, есть решение: можно воспользоваться специальным макросом, который будет автоматически обновлять все ваши поля при каждом открытии документа.

Для этого разместите приведенный ниже код макроса в ваш шаблон Normal.dot (Normal.dotm), на основе которого вы создаете свои документы, или в конкретный документ (P.S.: макрос обновлен 27.03.2008, так как Оглавление в документе не обновлялось, если это не сделать явным образом).

Если вы желаете обновлять поля вручную, то измените наименование макроса, создайте для него кнопку и разместите ее на панели инструментов (для Word 2003) или на панели быстрого доступа (для Word 2007).

Если вы не знаете, как подключить к документу и применить этот макрос, изучите следующие заметки с сайта:

Вы можете помочь в развитии сайта, сделав пожертвование:

Или помочь сайту популярной криптовалютой:

BTC Адрес: 1Pi3a4c6sJPbfF2sSYR2noy61DMBkncSTQ

ETH Адрес: 0x7d046a6eaa1bd712f7a6937b042e9eee4998f634

LTC Адрес: LUyT9HtGjtDyLDyEbLJZ8WZWGYUr537qbZ

DOGE Адрес: DENN2ncxBc6CcgY8SbcHGpAF87siBVq4tU

BAT Адрес: 0x7d046a6eaa1bd712f7a6937b042e9eee4998f634

XRP Адрес: rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh Депозит Tag: 105314946

USDT (ERC-20) Адрес: 0x7d046a6eaa1bd712f7a6937b042e9eee4998f634

Яндекс Деньги: 410013576807538

Вебмани (R ещё работает): R140551758553 или Z216149053852

А тут весь список наших разных крипто адресов, может какой добрый человек пожертвует немного монет или токенов — получит плюсик в карму от нас 🙂 Благо Дарим, за любую помощь!

Я хочу способ обновления все поля в документе Word 2013. (Если он работает в других версиях, тем лучше; у меня первоначально была эта проблема с Word 2007, и с тех пор ничего не изменилось.) Это включает перекрестные ссылки, номера страниц, оглавлений, индексов, заголовков и т. д. Если он может быть обновлен нажатием F9 , Я хочу его обновить.

(теоретически обновление полей может привести к необходимости обновления других полей, например, более длинной таблицы содержание изменяет некоторые номера страниц в основном тексте. Забота об обычных делах достаточно хороша для меня. На самом деле, это нормально, если я запустить макрос два или три раза, прежде чем он стабилизируется. Я просто хочу иметь один макрос, который находит все.)

моя попытка до сих пор не обновляет поля в текстовых полях внутри рисунков. Как их обновить и что еще я пропустил?

EDIT: комбинируя ответ, данный с тем, что я уже had дает макрос, который, кажется, обновляет все (с помощью известный дефект).

6 ответов

зайдите в настройки печати, выберите Обновить поля. Затем перейдите в раздел Печать или предварительный просмотр документа.

Et voilà, все поля обновлены!

Я просто делаю Ctrl + на — выбрать все — и затем F9 обновить много.

хотя, это не заголовки и нижние колонтитулы, но они обновляются при печати/печати МСИО.

обновление

Я нашел следующий макрос. На быстрый тест обновления оглавления, поля в пунктах, поля в колонтитулы и поля в плавающий текст диаграмма коробки.

надеюсь, что охватывает все, что вам нужно, если нет пожалуйста, укажите, что это еще не обновление.

этой страница выглядит интересно:

Если вы используете Word 2007, процесс немного отличается: нажмите Кнопка Office и нажмите кнопку Word Опционы. Слово отображает слово Диалоговое окно. Нажмите Дополнительно в левой части диалогового окна. (Щелкните здесь, чтобы увидеть связанную фигуру.) В общей области (прокрутите немного вниз чтобы увидеть его), убедитесь, что обновление Флажок автоматические ссылки при открытии выбирать. Нажмите OK. Эта настройка следует убедиться, что все ваши ссылки всегда в актуальном состоянии. Если вы хотите обновите поля, когда документ открытый, вам нужно использовать макрос для выполнить задачу. Конкретно, вам нужно будет использовать либо AutoOpen или Автозакрытия макрос, в зависимости от хотите ли вы обновить поля при открытии или закрытии документа. Тот ниже приведен пример AutoOpen макрос можно использовать.

обратите внимание, что макрос делает, что что параметры установлены на force обновление полей и ссылок при происходит печать, затем она обновляет все члены коллекции полей в документе. Если вы, вместо этого, хотел обновить поля на закрывая, вы можете использовать этот макрос:

этот макрос намного короче, потому что никакая потребность установить параметры обновления при печати выход из документа.выход из документа.

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

Добрый день!

Прошу подсказать, как можно обновить поле типа (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

Понравилась статья? Поделить с друзьями:
  • Word нумерация строк в таблице автоматически
  • Word обновить все поля колонтитулах
  • Word нумерация страницы четная
  • Word обнаружено содержимое которое не удалось прочитать как исправить
  • Word нумерация страниц через одну