运行时错误 4198,命令失败,尝试将 ms Word 文档设置为打印视图时



我正在尝试将窗口视图设置为打印视图。

我在word中使用了"记录宏",以查看word如何建议我设置某些内容以打印视图。代码如下:

If ActiveWindow.View.SplitSpecial = wdPaneNone Then
    ActiveWindow.ActivePane.View.Type = wdPrintView
Else
    ActiveWindow.View.Type = wdPrintView
End If

每次,执行都会停止并给我上述错误。调试指出:

ActiveWindow.View.Type = wdPrintView

作为越野车线。我也试过:

If ActiveWindow.View.SplitSpecial = wdPaneNone Then
    ActiveDocument.ActiveWindow.View.Type = wdPrintView
Else
    ActiveWindow.View.SplitSpecial = wdPaneNone
    ActiveWindow.View.Type = wdPrintView
End If

当splitspecial为4(wdPanePrimaryFooter(时,问题似乎发生了。但是改变条件来解释这一点似乎行不通。如果我注释掉视图类型行,一切都很好。

有什么想法吗?

提前谢谢你。

编辑,这是整个块,但我无法在一半时间内复制此错误:

Sub pageNumber()
    ActiveDocument.Sections(ActiveDocument.Sections.Count) _
        .Footers(wdHeaderFooterPrimary).Range.Select
    With Selection
        .ParagraphFormat.Alignment = wdAlignParagraphCenter
        .TypeText Text:="Page "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "PAGE ", PreserveFormatting:=True
        .TypeText Text:=" of "
        .Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
            "NUMPAGES ", PreserveFormatting:=True
        .Collapse
    End With
    ActiveDocument.Content.Select
    Selection.Collapse wdCollapseStart
    If ActiveWindow.View.SplitSpecial = wdPaneNone Then
        ActiveDocument.ActiveWindow.View.Type = wdPrintView
    Else
        ActiveWindow.View.SplitSpecial = wdPaneNone
        ActiveWindow.View.Type = wdPrintView
    End If
End Sub

问题中的代码类型是使用宏录制器的结果。这个工具真的很棒,但是因为它只模仿用户操作,所以它创建的代码有时不是最佳的。特别是使用页眉和页脚会使生活变得比应有的更复杂......当代码选择页眉/页脚范围时,该范围会触发编辑这些窗格所需的旧 Word 2.0"窗格"的显示。Word 6.0 引入了所见即所得,窗格已"停用",仅在此上下文中显示。

使用页眉和页脚时,Range对象通常比使用 Selection 更可取。您可以将Range视为不可见的选择,其优点是:1.它不会移动实际选择。2. 任务需要可以有任意数量的Range对象,而只能有一个选择。

下面的代码示例获取页脚范围并向其添加内容。由于它永远不会更改选择,因此屏幕更安静,窗格永远不会显示(并且代码更快(。

使用范围相对简单,直到字段代码发挥作用。然后,需要做一些工作才能获得新材料遵循字段的"目标"点。

Sub pageNumber()
    Dim rngFooter As Word.Range
    Dim fld As Word.Field
    Set rngFooter = ActiveDocument.Sections(ActiveDocument.Sections.Count) _
        .Footers(wdHeaderFooterPrimary).Range
    With rngFooter
        .ParagraphFormat.Alignment = wdAlignParagraphCenter
        .Text = "Page "
        .Collapse wdCollapseEnd
        Set fld = .Fields.Add(Range:=rngFooter, Type:=wdFieldEmpty, Text:= _
            "PAGE ", PreserveFormatting:=False)
    End With
    Set rngFooter = fld.result
    With rngFooter
        'Move the end of the range outside the field
        .MoveStart wdCharacter, 1
        .InsertAfter " of "
        .Collapse wdCollapseEnd
        .Fields.Add Range:=rngFooter, Type:=wdFieldEmpty, Text:= _
            "NUMPAGES ", PreserveFormatting:=False
    End With
End Sub

最新更新