首页 > 解决方案 > 运行时错误 4198,命令失败,尝试将 ms word doc 设置为打印视图时

问题描述

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

我在 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

标签: vbamacosms-word

解决方案


问题中的代码类型是使用宏记录器的结果。这个工具真的很棒,但是因为它只模仿用户的行为,它创建的代码有时并不是最优的。尤其是使用页眉和页脚会使生活变得比应有的更复杂......当代码选择一个页眉/页脚范围时,会触发显示编辑这些所需的旧 Word 2.0“窗格”。Word 6.0 引入了 WYSIWYG 并且窗格已“停用”并且仅在此上下文中显示。

使用页眉和页脚时,Range对象通常比使用Selection. 您可以将 aRange视为不可见的选择,具有以下优点: 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

推荐阅读