如何检测用户是否单击文件 >> 打印为选项或从 MS word 中按 CTRL+P 或使用 VBA 代码的 Excel?

How to detect if user clicks on File >> Print as option or presses CTRL+P from within MS word or Excel using VBA code?

我想检测用户何时在 ms word 或 excel 中单击文件 >> 打印或 CTRL+P 并将此检测用于 运行 使用 vba 代码的批处理文件,这可能吗? 此代码应随程序自动启动。 我试图找到类似的代码,但找不到任何对我的需要有用的东西。

如有任何帮助,我们将不胜感激。

谢谢

我觉得你的问题写得模棱两可。乍一看,您似乎在试图区分这两种告诉文件打印的方法。我知道在 vba.

中没有办法做到这一点

但是,您可以拦截打印事件或命令。

另一个可能的含义是您希望您的过程 运行 每当用户尝试打印时。参见 Intercepting Events Like Save or Print by Word MVPs Dave Rado and Jonathon West. See also Application.WorkbookBeforePrint Event

请注意,这不会阻止屏幕截图或保存到另一个文件。你介意分享你为什么要这样做吗?你希望完成什么?

您可以使用 DocumentBeforePrint 和 WorkbookBeforePrint Events. Below quoted from linked pages on Intercepting Events and WorkBookBeforePrint documentation

A DocumentBeforePrint event procedure looks like this:

Private Sub oApp_DocumentBeforePrint(ByVal Doc As Document, _
 Cancel As Boolean)
    'Your code here
End Sub

If you want to prevent printing from occurring in certain circumstances, you can set the Cancel variable to True, e.g.:

Private Sub oApp_DocumentBeforePrint(ByVal Doc As Document, _
 Cancel As Boolean)
    Dim Result As Long
    Result = MsgBox("Have you checked the " & "printer for letterhead paper?", vbYesNo)
    If Result = vbNo Then Cancel = True
End Sub

来自Excel documentation

This example recalculates all worksheets in the workbook before printing anything.

Private Sub App_WorkbookBeforePrint(ByVal Wb As Workbook, _ 
 Cancel As Boolean) 
 For Each wk in Wb.Worksheets 
 wk.Calculate 
 Next 
End Sub

引用结束 Material

拦截命令而不是事件

另一种不太有效的方法是拦截实际的 命令。您可以将您的程序命名为 PrintPreviewAndPrint,并让另一个名为 FilePrintQuick 的程序 调用 您的程序 PrintPreviewAndPrint。 早期版本使用 FilePrint 和 FilePrintDefault。感谢@Timothy Rylatt 提供命令名称。 他补充说:Note that neither of these will intercept the backstage command accessed via File | Print. For that you need to use an event.

Sub PrintPreviewAndPrint()
  ' Your code here
End Sub

Sub FileQuick()
  FilePreviewAndPrint
End Sub

在 Word 中,这些将进入您的模板或 Global Template

在 Word 中,通过将模板放在 Word 启动文件夹.

中,将其设为 Global Template

正在处理这个 Global in Excel

我对 Excel 如何处理全局宏的理解远不如 Word。为了解决这个问题,我在 Microsoft Answers Excel 编程论坛中提出了自己的问题。这里有一个link to that question and the answers I received。从事该线程的 Andreas Klinger 是一位经验丰富且知识渊博的 Excel 程序员,而我不是。