Reputation: 23
I've been using interop to edit existing word documents. My problem is; i need to add a new field to document footer and that, to my suprise, deletes existing footer fields, so only the newly added field remains. There is no clear documentation about it and the result is rather unexpected. Below is my code:
foreach (Microsoft.Office.Interop.Word.Section wordSection in wordDocument.Sections)
{
Microsoft.Office.Interop.Word.HeadersFooters footers = wordSection.Footers;
foreach (HeaderFooter footer in footers)
{
footer.Range.Select();
Field f = appWord.ActiveWindow.Selection.Fields.Add(appWord.ActiveWindow.Selection.Range);
appWord.Selection.TypeText(footerText);
}
}
Upvotes: 1
Views: 1976
Reputation:
What you describe is expected behaviour, because ".Add" is not ".Append" or ".InsertAfter", where you might reasonably hope that the field would be tacked onto the end of the selection. If you select a piece of text in Word and issue the VBA command
Selection.Fields.Add Selection.Range
you will see much the same thing.
WHat you need to do is establish the precise range where you need to insert your field, and add it there. Ideally, avoid use of Selection altogether. So if you need the field to come at the beginning of the footer, you could start with the following VBA sample and translate it into C# (sorry, I don't have the energy right now).
Sub insertFieldAtStartOfSec1Footers()
Dim footer As HeaderFooter
Dim rng As Word.Range
For Each footer In ActiveDocument.Sections(1).Footers
Set rng = footer.Range
rng.Collapse wdCollapseStart
' Insert a simple SECTION field
rng.Fields.Add rng, WdFieldType.wdFieldEmpty, "SECTION", False
Set rng = Nothing
Next
End Sub
Upvotes: 1