'编译错误'-'需要对象'VBA代码

时间:2019-05-13 09:13:14

标签: excel vba ms-word word-vba

我正在尝试打印文档,但是却收到错误消息

  

“编译错误”-“需要对象”

然后突出显示该行

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

1 个答案:

答案 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错误消息。