2010-10-06 20:29:03 +0000 2010-10-06 20:29:03 +0000
97
97
Advertisement

Как обновить все поля в документе Word?

Advertisement

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

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

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

  • *

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

'' Update all the fields, indexes, etc. in the specified document.
Sub UpdateAllFieldsIn(doc As Document)
    '' Update tables. We do this first so that they contain all necessary
    '' entries and so extend to their final number of pages.
    Dim toc As TableOfContents
    For Each toc In doc.TablesOfContents
        toc.Update
    Next toc
    Dim tof As TableOfFigures
    For Each tof In doc.TablesOfFigures
        tof.Update
    Next tof
    '' Update fields everywhere. This includes updates of page numbers in
    '' tables (but would not add or remove entries). This also takes care of
    '' all index updates.
    Dim sr As range
    For Each sr In doc.StoryRanges
        sr.Fields.Update
        While Not (sr.NextStoryRange Is Nothing)
            Set sr = sr.NextStoryRange
            '' FIXME: for footnotes, endnotes and comments, I get a pop-up
            '' "Word cannot undo this action. Do you want to continue?"
            sr.Fields.Update
        Wend
    Next sr
End Sub
'' Update all the fields, indexes, etc. in the active document.
'' This is a parameterless subroutine so that it can be used interactively.
Sub UpdateAllFields()
    UpdateAllFieldsIn ActiveDocument
End Sub
Advertisement
Advertisement

Ответы (5)

82
82
82
2010-10-06 21:07:05 +0000

Я просто делаю Ctrl+A - чтобы выбрать все - и then F9 для обновления лота.

Хотя, это пропускает заголовки и колонтитулы, но они обновляются, когда вы печатаете/принт-предварительный просмотр IIRC.


Обновление

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

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

Source: _COPY16_macro.htm

Sub UpdateAll()
    Dim oStory As Range
    For Each oStory In ActiveDocument.StoryRanges
        oStory.Fields.Update
        If oStory.StoryType <> wdMainTextStory Then
            While Not (oStory.NextStoryRange Is Nothing)
                Set oStory = oStory.NextStoryRange
                oStory.Fields.Update
            Wend
        End If
    Next oStory
    Set oStory = Nothing
End Sub
37
37
37
2015-09-15 13:27:49 +0000

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

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

4
Advertisement
4
4
2013-07-18 19:24:25 +0000
Advertisement

Слово 2010:

Щелкните правой кнопкой мыши на ленте, настроить ленту, выберите команду из “все команды” поиск “обновление” и добавить его туда, где вы хотите.

Эта кнопка обновляет только выбранные поля. Затем, чтобы обновить все поля, нажмите Ctrl + A затем эта кнопка.

3
3
3
2015-02-18 19:32:08 +0000

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

Dim oStory As Range
    Dim oSection As Object
    Dim oHeader As Object
    Dim oFooter As Object

    For Each oStory In ActiveDocument.StoryRanges
        oStory.Fields.Update
    Next oStory

        For Each oSection In ActiveDocument.Sections
             For Each oHeader In oSection.Headers
                 oHeader.Range.Fields.Update
             Next oHeader

             For Each oFooter In oSection.Footers
                 oFooter.Range.Fields.Update
             Next oFooter
        Next oSection
2
Advertisement
2
2
2016-06-15 20:59:23 +0000
Advertisement

Для C#:

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main(string[] args)
    {
        List<string> path = new List<string>(args);

        string filePathstr = string.Join(" ", path.ToArray());
        //System.Windows.Forms.MessageBox.Show("filepathstr: " + filePathstr);

        string folderPathstr = Path.GetDirectoryName(filePathstr);
        //System.Windows.Forms.MessageBox.Show("folderPathstr: " + folderPathstr);

        try
        {
            Application ap = new Application();
            Document document = ap.Documents.Open(filePathstr);
            document.Fields.Update();

            foreach (Section section in document.Sections)
            {
                document.Fields.Update(); // update each section

                HeadersFooters headers = section.Headers; //Get all headers
                foreach (HeaderFooter header in headers)
                {
                    Fields fields = header.Range.Fields;
                    foreach (Field field in fields)
                    {
                        field.Update(); // update all fields in headers
                    }
                }

                HeadersFooters footers = section.Footers; //Get all footers
                foreach (HeaderFooter footer in footers)
                {
                    Fields fields = footer.Range.Fields;
                    foreach (Field field in fields)
                    {
                        field.Update(); //update all fields in footers
                    }
                }
            }    

            document.Save();
            document.Close();

        }
        catch (NullReferenceException)
        {
            System.Windows.Forms.MessageBox.Show("A valid file was not selected.");
        }
    }
}
Advertisement

Похожие вопросы

13
3
7
10
1
Advertisement