7 年后,但在我的 中使用 Joe W 的答案时Word VSTO Addin
,我遇到了一个问题并决定在此处发布修复:
BeforeView.SeekView
设置为WdSeekView.wdSeekCurrentPageHeader
or WdSeekView.wdSeekCurrentPageFooter
,检查是否View.SeekView
已设置为页眉或页脚值。如果是,则抛出异常,因为当前View.SeekView
无法更改为wdSeekCurrentPageHeader
ifView.SeekView
已设置为页眉值,并且当前View.SeekView
无法更改为wdSeekCurrentPageFooter
ifView.SeekView
已设置为页脚值。如果在执行代码以调整视图设置(例如,在 Word VSTO 插件中)时用户正在编辑页眉或页脚,则可能会出现这种情况。
此代码有效。它包括View.SeekView
在调用之前保存设置的代码,SetView
并在调用SetView
. 这考虑到用户在SetView
被调用时正在编辑页眉或页脚的场景,这可能是Word VSTO Addin
.
// ... some Word VSTO Addin code that calls SetView
Word.WdSeekView enumSavedSeekView = Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView;
bool viewResetNeeded = SetView(workingStoryRange);
if (viewResetNeeded)
{
Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView = enumSavedSeekView;
}
// ... end of some Word VSTO Addin code that calls SetView
private bool SetView(Word.Range range)
{
bool viewResetNeeded = false;
// wdNormalView == Draft View, where SeekView can't be used and isn't needed.
if (Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.Type != Word.WdViewType.wdNormalView)
{
// -1 Not Header/Footer, 0 Even page header, 1 Odd page header, 4 First page header
// 2 Even page footer, 3 Odd page footer, 5 First page footer
switch (range.Information[Word.WdInformation.wdHeaderFooterType])
{
case 0:
case 1:
case 4:
if ((Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekEvenPagesHeader) && (Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekFirstPageHeader) && (Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekPrimaryHeader))
{
Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
viewResetNeeded = true;
}
break;
case 2:
case 3:
case 5:
if ((Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekEvenPagesFooter) && (Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekFirstPageFooter) && (Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView != Word.WdSeekView.wdSeekPrimaryFooter))
{
Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
viewResetNeeded = true;
}
break;
default:
break;
}
}
return viewResetNeeded;