I agree with your comment Fumei
Thought that CurIndex would increment on each SectionBreak.
Tried your code but sadly still having the same error. I've cut and paste
the sub to an Access module with option explicit, add a few object but cannot
figure out why ?
Sub test()
Dim wrd As Word.Application
Dim doc As Word.Document
Dim MyArray As Variant
Dim Tbl As Word.Table
Dim oHF As Word.HeaderFooter
Dim CurIndex As Long
Dim x As Integer
MyArray = Split("aaaa bbbb cccc dddd eeee ffff")
Set wrd = CreateObject("Word.Application")
Set doc = wrd.Documents.Add
wrd.Visible = True
CurIndex = 1
wrd.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = True
For x = 0 To UBound(MyArray)
Set Tbl = wrd.ActiveDocument.Tables.Add(wrd.Selection.Range, 1, 2)
Tbl.Cell(1, 1).Range.Text = MyArray(x)
' action Header as object
Set oHF =
wrd.ActiveDocument.Sections(CurIndex).Headers(wdHeaderFooterFirstPage)
With oHF
.LinkToPrevious = False
.Range.Tables.Add Range:=oHF.Range, numrows:=1, numcolumns:=2
.Range.Tables(1).Cell(1, 1).Range.Text = "Header for " & MyArray(x)
.Range.Tables(1).Cell(1, 2).Range.Text = "Header"
End With
' action Footer as object
Set oHF =
wrd.ActiveDocument.Sections(CurIndex).Footers(wdHeaderFooterFirstPage)
With oHF
.LinkToPrevious = False
.Range.Tables.Add Range:=oHF.Range, numrows:=1, numcolumns:=2
.Range.Tables(1).Cell(1, 1).Range.Text = "Footer for " & MyArray(x)
.Range.Tables(1).Cell(1, 2).Range.Text = "Footer"
End With
' go to end of document
With wrd.Selection
.EndKey Unit:=6 ' this is wdStory
.InsertBreak Type:=wdSectionBreakNextPage
' Selection will move into that Section
' so Set Tbl using wrd.Selection should work
End With
' increment CurIndex
CurIndex = CurIndex + 1
Next x
End Sub
------------------------------------
"fumei via OfficeKB.com" wrote:
> For one thing, CurIndex is not incremented. You may want to try using a
> HeaderFooter object to do your head and footer work. try this. I moved the
> CurIndex initializing out of the loop, as well as the DifferentFirstPage. If
> DifferentFirstPage is to apply for all Sections, you may as well do once, at
> the beginning. It should apply for the entire document.
>
> There is no need to set a range object for the table in the document. Just
> put the text into the cells.