Preventing "Command Not Found" errors when changing Word's headers/footers in VBA
I found various threads on the Web from people complaining about Command Not Found errors when using macros that change Word’s headers and footers.
The solution seems to be to repaginate every time you change a header/footer pair. (Of course, it could just be a timing issue, but repaginating does seem to work.)
Here is some example VBA code that sets the headers and footers for all sections to match those of the first:
Dim mySection As Section
Dim myHeaderFooter As HeaderFooter
For Each mySection In ActiveDocument.Range.Sections
If mySection.index > 1 Then
For Each myHeaderFooter In mySection.Headers
If myHeaderFooter.Exists Then
myHeaderFooter.LinkToPrevious = True
End If
Next myHeaderFooter
For Each myHeaderFooter In mySection.Footers
If myHeaderFooter.Exists Then
myHeaderFooter.LinkToPrevious = True
End If
Next myHeaderFooter
End If
ActiveDocument.Repaginate ' prevent potential Command Not Available error
Next mySection
Without the Repaginate
call on the penultimate line I was getting Command
Not Found errors when setting LinkToPrevious
to True
; with the
repagination, it worked okay.