我正在尝试打印文档,但是却收到错误消息
“编译错误”-“需要对象”
然后突出显示该行
Set previousPrinter = objWord.**ActivePrinter**
我正在使用以下代码:
Private Sub CommandButton1_Click()
Dim previousPrinter
Dim objWord As New Word.Application
Set previousPrinter = objWord.ActivePrinter
objWord.ActivePrinter = "Followprint"
On Error GoTo CLOSE_WORD_APP 'error handling to ensure there will not be any orphaned and invisible Word application left
Dim doc As Word.Document
Set doc = objWord.Documents.Open("test.docx")
doc.Variables("refBook").Value = Me.txtRef.Text
doc.Fields.Update
doc.Save
objDoc.PrintOut
' Restore the original printer
objWord.ActivePrinter = previousPrinter
doc.Close
CLOSE_WORD_APP:
objWord.Quit SaveChanges:=False
End Sub
答案 0 :(得分:2)
ActivePrinter
返回带有打印机名称而不是对象名称的字符串。因此,将previousPrinter
声明为字符串,并简单地将ActivePrinter
的结果分配给它。
Dim previousPrinter as String
Dim objWord As New Word.Application
previousPrinter = objWord.ActivePrinter
objWord.ActivePrinter = "Followprint"
(...)
在VBA中,关键字Set
仅用于将 object 分配给变量(例如,Documents.Open
函数的结果)。如果在尝试分配不是对象的任何东西时使用它,则编译器(或运行时)将抛出Object required
错误消息。