Question : Looping thru 4 sections, changing field codes in headers

With the cursor residing in some section of my document, I would like to perform the following:

- Access the ODD page and EVEN page header of the section where the cursor currently resides in and change the field code {REF bookmark_DE \h} to {REF bookmark_EN \h} using VBA. (That's what the below code is doing)

- The code should THEN GO ON on and loop thru the following 3 (three) sections and change the existing field code {REF bookmark_DE \h} in the even and odd page headers in the following order to ...
{REF bookmark_ES \h}
{REF bookmark_FR \h}
{REF bookmark_IT \h}

I hope this is feasible.

Thank you very much in advance for your help.

Regards, Andreas
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
Sub ModifyHeaderFields()
    Dim sec As Word.Section
    Dim rng As Word.Range
    Dim fld As Word.Field
    Dim h As Word.WdHeaderFooterIndex
    
    Set rng = Selection.Range
    Set sec = rng.Sections(1)
    For h = wdHeaderFooterPrimary To wdHeaderFooterEvenPages Step 2 'omit first page header
        For Each fld In sec.Headers(h).Range.Fields
            fld.Code.Text = Replace(fld.Code.Text, "REF bookmark_DE \h", "REF bookmark_EN \h")
        Next fld
    Next h
End Sub

Answer : Looping thru 4 sections, changing field codes in headers

Here is one I prepared earlier (before lunch)
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
Sub ModifyHeaderFields()
    Dim sec As Word.Section
    Dim fld As Word.Field
    Dim s As Integer
    Dim secStart As Integer
    Dim langs() As String
    Dim h As Word.WdHeaderFooterIndex
    
    langs = Split("EN,ES,FR,IT", ",")
    
    secStart = Selection.Sections(1).Index
    For s = 0 To 3
        Set sec = ActiveDocument.Sections(secStart + s)
        For h = wdHeaderFooterPrimary To wdHeaderFooterEvenPages Step 2 'omit first page header
            For Each fld In sec.Headers(h).Range.Fields
                If fld.Type = wdFieldRef Then
                    fld.Code.Text = Replace(fld.Code.Text, "bookmark_DE", "bookmark_" & langs(s))
                    fld.Update
                End If
            Next fld
        Next h
    Next s
End Sub
Random Solutions  
 
programming4us programming4us