I’m working on a VBA macro for Microsoft Word and need to replace page number fields in headers and footers with plain text. Specifically, I want to:
- Replace all page number fields in headers and footers with plain
text. - Remove the fields without leaving any remaining field codes.
I tried using fld.Result.InsertBefore
and fld.Result.InsertAfter
to insert the text next to the fields, but these methods don’t work as expected.
Sub EliminarCodigosCampo()
Dim sec As Section
Dim hdr As HeaderFooter
Dim ftr As HeaderFooter
Dim fld As Field
Dim fieldText As String
' Select the entire content of the document
Selection.WholeStory
Selection.Fields.Unlink
' Convert automatic numbering to text
ActiveDocument.ConvertNumbersToText
' First pass: Copy the page number field value and insert it as plain text
For Each sec In ActiveDocument.Sections
' Loop through all headers
For Each hdr In sec.Headers
For Each fld In hdr.Range.Fields
fieldText = fld.Result.Text
fld.Result.InsertBefore fieldText
Next fld
Next hdr
' Loop through all footers
For Each ftr In sec.Footers
For Each fld In ftr.Range.Fields
fieldText = fld.Result.Text
fld.Result.InsertBefore fieldText
Next fld
Next ftr
Next sec
' Second pass: Remove page number fields and their content
For Each sec In ActiveDocument.Sections
' Loop through all headers
For Each hdr In sec.Headers
Do While hdr.Range.Fields.Count > 0
hdr.Range.Fields(1).Unlink
hdr.Range.Fields(1).Result.Delete
Loop
Next hdr
' Loop through all footers
For Each ftr In sec.Footers
Do While ftr.Range.Fields.Count > 0
ftr.Range.Fields(1).Unlink
ftr.Range.Fields(1).Result.Delete
Loop
Next ftr
Next sec
End Sub
Problem:
The methods fld.Result.InsertBefore
and fld.Result.InsertAfter
don’t seem to work as intended. How can I correctly replace page number fields in headers and footers with plain text using VBA?
Any guidance or suggestions would be greatly appreciated!
1