如何检查word文档是否已打印

时间:2012-07-16 18:28:55

标签: vba ms-word word-vba word-2003

我想只在文件已经打印的情况下启用另一个功能“代码”,我正在考虑的事情

Sub Testing
    Dim hasPrinted as boolean
    If ActiveDocument.PrintOut = True Then
        hasPrinted = True
        call code here...
    Else
        hasPrinted = False
        MsgBox "Please Print Before Adding"
    End If
End Sub

我收到“ActiveDocument.PrintOut”行上的“编译错误,预期函数或变量”错误。谁能给我一些指示?

2 个答案:

答案 0 :(得分:2)

在Word VBA中捕获打印事件并不是一件容易的事。然而,这是一个巧妙的技巧:)

为此,请执行以下操作

创建一个类模块,说Class1并粘贴此代码

Option Explicit

Public WithEvents oApp As Word.Application

Private Sub oApp_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
    ActiveDocument.Bookmarks("DocWasPrinted").Delete
    With ActiveDocument.Bookmarks
        .Add Range:=Selection.Range, Name:="DocWasPrinted"
        .DefaultSorting = wdSortByName
        .ShowHidden = True
    End With
End Sub

现在插入一个模块并粘贴此代码

Option Explicit

Dim oAppClass As New Class1

Public Sub AutoExec()
    Set oAppClass.oApp = Word.Application
End Sub

Sub Testing()
    If hasPrinted = True Then
        MsgBox "Document was printed"
        '~~> Call your code
    Else
        MsgBox "Please Print Before Adding"
    End If
End Sub

Function hasPrinted() As Boolean
    If ActiveDocument.Bookmarks.Exists("DocWasPrinted") = True Then
        hasPrinted = True
    End If
End Function

关闭文档并重新打开。现在测试一下。

<强> LOGIC:

这段代码的作用是当用户打印文档时,代码会创建一个名为DocWasPrinted的隐藏书签。在我的代码中,我会检查书签是否已创建。

请记住删除文档退出时的书签。

Private Sub Document_Close()
     ActiveDocument.Bookmarks("DoWasPrinted").Delete
End Sub

答案 1 :(得分:1)

This question提供有关创建生产班次Document After Print事件的信息。

完成后,您可以将布尔值更新为true以指示文档已打印。 Word本身不存储此信息。