If you have any problems with this web page, please first read my browser notesbrowser notes [link to ../../Miscellany/Browsers/Browsers.php] and if you still have issues, feel free to e-mail mee-mail me [link to e-mail the author at mailto:Tony@WordArticles.com]

Updating Index Fields

Indexes

I just updated my Index. Where did my Page Headers go?

Summary

Sometimes, when you update an Index Field, your Page Headers can change, or disappear; sometimes your page formatting may change. These effects can happen when you have an Index formatted with an explicit number of columns and you have different formatting of the body of the Document before and after the Index.

This, rather long, article explains the causes, explains why some workarounds don't work and offers one that does.

A Brief Reminder

When you delete a Section Break, you are, in effect, merging two Sections into one. It may be that the Section-specific settings in each of the two Sections differ, in which case Word has to make a decision about how to resolve the clash(es).

Word is not clever about this. When the Section Break is deleted all the settings effectively stored within it – Headers, Footers, Page Setup Details (orientation, margins, etc.), Page Borders, and Forms Protection – are also deleted, without so much as a ‘by your leave’. This leaves the Section before the break with no settings and Word, like nature, abhorring a vacuum, fills the gap with the only settings it has to hand, those of the Section following the Break.

Before going any further, it is worth pointing out that the behaviour is exactly the same when you delete an entire Section. In this case, quite reasonably, the Section following it remains just as it was before. Actually, deleting a whole Section suffers the same issues as deleting just a Break, but that isn't really relevant here.

Of particular interest at the moment are Headers and Footers. Headers and Footers of Sections are not totally independent: it is possible to specify that one is the same as the previous one, or linked to the previous one (Word seems to use the two terms interchangeably). When you do this, the Header or Footer information is stored in the earlier, or earliest, Section and referred to by the later Sections.

When the Header and Footer information of a Section has been deleted, by deletion of the Section Break, it is no longer there and can no longer be referred to by later Sections. Word is aware of this possibility and takes steps to replace references with the actual information when necessary.

A Quirk: Deleting Sections

There had to be one, hadn’t there, or I wouldn’t be writing this? Truth is, there are several quirks; some of them are described on the Word MVPs’ site, herethe Word MVPs’ site, here [link to the Word MVPs’ site at http://www.word.mvps.org/FAQs/Formatting/WorkWithSections.htm], although not specifically the one currently of interest.

Word, at least in the particular circumstance of deletion of a Section break, seems unaware of the possibility that some, but not all, Headers and Footers in a Section may be linked to previous ones. All the careful steps it takes to ensure that data are not lost, are only taken when all the Headers and Footers of a Section, whether used or not, are set to be the same as previous. Just one difference is enough to make Word throw caution to the winds and delete all the Headers and Footers from the Section before the Break being deleted.

Just a stylised bullet Perhaps an Example will make it clearer

⇒ Perhaps an Example will make it clearer [link to HeaderExample.php on this site]

A Quirk: Deleting Paragraphs

Just as with Sections, when you delete a Paragraph Mark you are, in effect, merging two paragraphs into one. It may be that the paragraph-specific settings in each of the two paragraphs differ, in which case Word has, again, to make a decision about how to resolve the clash(es).

Word is not clever about this either. When a Paragraph Mark is deleted all the settings effectively stored within it – the Style in use, etc., I do not propose to list them all – are kept and applied to the new single paragraph; this time, it is the settings of the second paragraph that are unceremoniously dumped. I believe that, once upon a time, Paragraphs used to behave in the same way as Sections (and apply the formatting of the second paragraph to the new, merged, one) but that was pre-Word 95, and isn't really relevant now.

If you delete an entire paragraph in one fell swoop, however, Word doesn’t view that as merging two paragraphs and it does not apply the settings from the deleted paragraph to the one that follows it. Quite right, too.

The reason for introducing Paragraphs into this discussion is that every Section Break contains an implicit Paragraph Mark; the end of a section is always the end of a paragraph as well. When you delete a Section Break you are also deleting the implicit Paragraph Mark and, as a result, there are two possibilities: either you are deleting a paragraph mark with the result that two paragraphs are being merged, or you are deleting an entire paragraph.

The first of these possibilities, when you do not have an explicit paragraph mark immediately preceding the Section Break, and when you are, thus, merging the paragraph that ended with (the implicit paragraph mark in) the Section Break, results in the newly merged paragraph having the style of the one previously before the Section Break. This effect can sometimes surprise but is wholly explainable and easily avoidable, by adding an explicit paragraph mark at the end of the section.

The second possibility, when you do have an explicit paragraph mark at the end of the Section, ought to be straightforward. When you delete the Section Break you are deleting an entire paragraph and so no paragraph formatting should change. Most of the time this works as you might expect.

When, however, you have a Section Break in a paragraph all by itself as the first paragraph inside a Field result, and you delete the Section Break, it acts as though it were not in a paragraph by itself, and the formatting of the paragraph containing the Section Break is applied to the paragraph after it.

Just a stylised bullet Click here for a detailed step-by-step example of this

⇒ Click here for a detailed step-by-step example of this [link to ParagraphExample.php on this site]

Now a Look at Indexes

Before you can add an index to a Word Document you must tell Word about the elements you want to appear in it, either directly or by using a concordance file. Further details of this process are beyond the scope of this article, which assumes that this prerequisite has been completed. If you are interested there is an article on the subject on the Word MVPs’ site, herethe Word MVPs’ site, here [link to the Word MVPs’ site at http://www.word.mvps.org/FAQs/Formatting/WorkWithSections.htm].

When you create an index you tell Word, amongst other things, which Index Entry (XE) Fields to use and, the focus of this article, how many (text) columns you want the index to have.

Screenshot: The Insert Index Dialog
The Insert Index Dialog

If, after inserting an Index using the default values shown in the Dialog above, you look at the Field Code inserted (by pressing Alt+F9) you will see something like:

{ INDEX \c “2” \z “2057” }

“2057” is the code for U.K. English and the \c “2” switch is what explicitly tells Word to create a two-column index.

You can specify the columns as a number in the range 1 — 4, or as “Auto”, meaning the same number of columns as the surrounding text. If you explicitly specify a number, Word will assume that this is, or may be, a different number of columns from the surrounding text and will create the index in a Document Section all by itself, bounding it with two Continuous Section Breaks:

Screenshot: Part of a Document showing an Index
Part of a Document showing an Index

In what might appear, to the uninitiated, to be a slight deception, whether, and how obviously, Word shows these Section Breaks depends on several factors; they are, however, always clearly shown in Normal, now renamed Draft, View:

Screenshot: Part of a Document showing an Index (Draft View)
The same part of the Document in Draft (Normal) View

In both the above screenshots I have Field Shading set to “When selected” and you can see, if you look closely enough, that the Index Field is considered Selected when the cursor is in the Section Break but Word does not exactly make it obvious. It is, however, important to understand that the breaks are part of the Field Result.

When the Index is first inserted, two new Section Breaks are inserted, making three sections out of the existing one:

If any XE Fields are inserted or changed, or any part of the Document is changed or even if it isn't, you can update the Index, and:

The Problem

The fun starts when, after inserting an Index with Section Breaks, any of the Headers and/or Footers (or, indeed, other properties, such as page orientation or number of columns) of the Section after the Index are changed. Then, when the Index is updated:

A Possible Solution

Updating the Index Field is a single operation and no amount of understanding of the component elements of it really helps in overcoming the problem. Action must be taken both before and after the process to make sure the Headers and Footers are correctly maintained, or perhaps recovered would be a better word.

The Header and Footer information that is lost is held in the first Section Break of the Index, the Break that terminates the Section before the Index. Saving that would seem like a good place to start, and one way to save it, temporarily, is to copy it to the Clipboard. If you were to do this before updating the Index, you would then have all the information saved and would just need a mechanism for putting it all back together in the right sequence after the update.

Pasting a Section Break, complete with Section attributes, into a Document is a fundamentally different action from inserting an 'empty' Break. When you paste, Word assumes you know what you're doing and makes no effort to compensate for any effects of the operation. If you could simply paste your copied Section Break over the top of the one that had replaced it the problem would be solved.

Things are never easy, however, and if you do just paste, you will see the effect, described above, of an unexpected and unwanted Style change. It appears as though, behind the scenes, the paste is actually performed as two separate actions, the first of which is deletion of the selected Section Break in its own paragraph with its concomitant problem, and only after the damage has been done are the contents of the Clipboard pasted in.

It is necessary, therefore, to take a slightly more roundabout route to the desired goal and to make sure that the deletion does not happen first. Now, I cannot explain why, but if, instead of pasting in the Section Break, you insert it from an AutoText, you do not hit the problem. Using AutoTexts also removes the limitation of only being able to remember one set of Section attributes at a time, that was inherent in the use of the Clipboard. As you will see later, this could, in theory at least, be significant.

All that was not easy to write and, I suspect, was not easy to read either. So, I hope that ...

Just a stylised bullet A step-by-step example will make this clearer

⇒ A step-by-step example will make this clearer [link to PictorialUpdateFix.php on this site]

Making it Easier to Use

Finding a solution that works is only half the battle. If it's awkward to use, especially when it is relatively infrequently needed, it won't be used, or it won't be used correctly and won't, therefore, be effective. You need a way to automate it so it's now time to look at writing some VBA code.

Code to do the job is simply presented here. Some explanation of what it does, and why, is presented on a separate page.

Sub ProcessFields()

    Dim NumFields       As Long
    
    Dim TemplateSaved   As Boolean
    Dim AutoTextPrefix  As String
    Dim AutoTextCount   As Long
    Dim AutoTextName    As String
    Dim AutoTexts       As Word.AutoTextEntries
    Dim OneField        As Word.Field

    NumFields = NumberOfFields(Selection.Range)

    With Selection.Range

        .TextRetrievalMode.IncludeFieldCodes = True
        
        While .Fields.Count < NumFields
            .MoveEndUntil Chr(&H15)
            .MoveEnd wdCharacter, 1
        Wend
    
        TemplateSaved = .Document.AttachedTemplate.Saved
        Set AutoTexts = .Document.AttachedTemplate.AutoTextEntries
        AutoTextPrefix = Chr$(28) & "Section" & Chr$(28) & "Break" & Chr$(28)
        AutoTextCount = 0
            
        For Each OneField In .Fields
            If OneField.Type = wdFieldIndex Then
                AutoTextCount = AutoTextCount + 1
                AutoTextName = AutoTextPrefix & CStr(AutoTextCount)
            
                On Error Resume Next
                    AutoTexts(AutoTextName).Delete
                On Error GoTo 0
                
                With OneField.Result
                    If .Sections.Count > 1 Then ' Nothing to do if no breaks
                        .Collapse wdCollapseStart
                        .MoveEnd wdCharacter, 1
                        AutoTexts.Add AutoTextName, Range:=.Duplicate
                    End If
                End With

            End If
        Next OneField
        
        .Fields.Update
    
        AutoTextCount = 0
        
        For Each OneField In .Fields
            If OneField.Type = wdFieldIndex Then
                AutoTextCount = AutoTextCount + 1
                AutoTextName = AutoTextPrefix & CStr(AutoTextCount)
                
                With OneField.Result
                    If .Sections.Count > 1 Then ' Do nothing if no Break
                        .Collapse wdCollapseStart
                        .MoveEnd wdCharacter, 1
                        On Error Resume Next
                            ' Will fail (code 5941) if no saved Break
                            AutoTexts(AutoTextName).Insert .Duplicate, True
                        On Error GoTo 0
                    End If
                End With
                
                On Error Resume Next
                    AutoTexts(AutoTextName).Delete
                On Error GoTo 0
                
            End If
        Next OneField
        
        .Document.AttachedTemplate.Saved = TemplateSaved
        
    End With

End Sub
 
Function NumberOfFields(RangeI As Word.Range) As Long Dim FieldsB As Long Dim FieldsA As Long Dim FieldsT As Long ' Total Dim Story As Word.Range Set Story = ActiveDocument.StoryRanges(RangeI.StoryType) With ActiveDocument.StoryRanges(RangeI.StoryType) FieldsT = .Fields.Count .SetRange Story.Start, RangeI.Start - (Len(RangeI.Text) = 0) FieldsB = .Fields.Count .SetRange RangeI.End, Story.End FieldsA = .Fields.Count End With NumberOfFields = Abs(FieldsA + FieldsB - FieldsT) End Function

Just a stylised bullet Excruciating detail of the code can be seen here

⇒ Excruciating detail of the code can be seen here [link to CodeExample.php on this site]

Now you have an automated procedure, all that remains is to find a way to invoke it. In keeping with everything else I have shown here, I would like to use Word 2007 to demonstrate; unfortunately, Word 2007 does not offer a way to update Pop-up menus through the User Interface so you must use VBA. I am not going to describe this, I’m just going to tell you to do it:

If you know what you’re doing with this, I will leave you to get on with it. If not, take a look at the instructions for installing macros on Graham Mayor’s web siteinstructions for installing macros on Graham Mayor’s web site [link to http://www.gmayor.com/installing_macro.htm], and, when you have your macros installed, and assuming they are in your Normal Template, come back and run the following code:

Sub TweakMenu()
    
    With CommandBars("Fields")
        With .Controls.Add(Before:=.FindControl(ID:=215).Index + 1)
            .Caption = "Update Field Safely"
            .OnAction = "ProcessFields"
        End With
    End With
End Sub

When you have done that, if you right click on a Field (any Field) in your Document, you should see this.

Screenshot: Using the New Update Menu option
Using your new code from the Fields Context Menu

Selecting “Update Field” will do as it always did. Selecting “Update Field Safely” will, instead, run the code described and shown here. In closing I will just point out one small effect of running this procedure: should you wish to Undo it, you will need to Undo two commands, the replacement of the Section Break (done in the code) and then the actual Field Update.

Finally ...

That's about all I have to say on this subject. When I started writing, it never crossed my mind I would write as much as I have. I hope somebody gets some benefit from it but, if not, I already have, so it has not been a completely wasted effort. At least one of the issues presented here is probably a bug but I doubt it will ever be a high priority one. Given that a workaround is possible, even if somewhat awkward, I shan’t be holding my breath waiting for a fix.