Word- VBA- 如何在打印前自动运行编码?

Word- VBA- How To Automatically Run Code Before Printing?

文档默认有底纹 wdColorGray25。我希望能够在打印(或另存为 PDF)之前删除所有阴影,但这似乎不像 Excel 中那样简单(代码在标准模块中本身可以正常工作)。

Private Sub appWord_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorAutomatic
        End With
    End With
End Sub

换句话说,如果我按Ctrl+P,文档将在打印前去除底纹,然后在打印后重新应用。还希望更改也反映在打印预览中。

如果我 select FilePrint 命令并点击 Create 它会生成以下代码(不是 Application.PrintOut ):

Sub FilePrint()
'
' FilePrint Macro
' Prints the active document
'
    Dialogs(wdDialogFilePrint).Show

End Sub

如果我修改代码为:

Sub PrintOut()
' PrintOut runs when you use Ctrl + P

    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorAutomatic
        End With
    End With

    Application.PrintOut
    
    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorGray25
        End With
    End With
    

End Sub

然后按Ctrl+P,你可以从下面的截图中看到文字底纹仍然出现。

但是,如果我像下面这样更改子名称,它将在没有底纹的情况下打印,但不会出现打印预览窗格(它只是直接打印,中间没有任何提示)。

Sub PrintPreviewandPrint()
' PrintOut runs when you use Ctrl + P

    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorAutomatic
        End With
    End With

    Application.PrintOut
    
    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorGray25
        End With
    End With
    

End Sub

在Word中,您可以捕获内置命令来修改它们。要查看其工作原理,请尝试以下步骤:

  1. 在 Word 中,选择 开发人员>宏
  2. 中的宏下拉列表更改为 Word 命令
  3. 查找并selectFilePrint.
  4. 中的宏下拉列表改回 Normal.dotm.
  5. 单击创建 按钮。 Word 会创建一个以命令名称命名的新宏。
Sub PrintOut()
' PrintOut runs when you use Ctrl + P

    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorAutomatic
        End With
    End With

    Application.PrintOut
    
    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorGray25
        End With
    End With
    

End Sub
Sub FilePrint()
'
' FilePrint Macro
' Prints the active document
'

    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorAutomatic
        End With
    End With

    Dialogs(wdDialogFilePrint).Show

    With ActiveDocument.Styles("example").Font
        With .Shading
            .BackgroundPatternColor = wdColorGray25
        End With
    End With


End Sub

现在添加您的代码以修改 Dialogs 行前后的样式,删除之前的阴影并在之后添加。