Code: Select all
Application application = new Application();
// Just for debugging.
application.Visible = true;
Document document = application.Documents.Open(filename);
foreach (Section section in document.Sections)
{
HeaderFooter header = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
if (header == null || !header.Exists || header.LinkToPrevious)
{
// Header is disabled or linked to previous section.
continue;
}
// We need to swith the view, otherwise some operations in the header
// might fail.
// This code is from a recorded Word macro.
Window activeWindow = application.ActiveWindow;
if (activeWindow.View.SplitSpecial != WdSpecialPane.wdPaneNone &&
activeWindow.Panes.Count > 1)
{
activeWindow.Panes[2].Close();
}
activeWindow.ActivePane.View.Type = WdViewType.wdPrintView;
activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
// Get the full range of the header. This call causes my problem.
Range headerRange = header.Range;
// I'm doing something with 'headerRange' here, but this doesn't affect
// the problem.
// This switches the current view out of the header. Usually this also
// deletes the header if it is empty. But if I accessed 'header.Range'
// it doesn't delete it. Why?
activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
}
application.Quit(SaveChanges: WdSaveOptions.wdDoNotSaveChanges);