简体   繁体   English

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

[英]'Compile Error' - 'Object required' VBA Code

I am trying to print a document however I am receiving the error我正在尝试打印文档,但收到错误

'Compile Error' - 'Object required' “编译错误”-“需要对象”

and then it highlights the line然后突出显示该行

 Set previousPrinter = objWord.ActivePrinter

I am using the following code:我正在使用以下代码:

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

ActivePrinter returns a string with the name of the printer, not an object. ActivePrinter返回一个带有打印机名称的字符串,而不是一个对象。 Therefore, declare previousPrinter as string and simply assign the result of ActivePrinter to it.因此,将previousPrinter声明为字符串并简单地将ActivePrinter的结果分配给它。

Dim previousPrinter as String
Dim objWord As New Word.Application

previousPrinter = objWord.ActivePrinter
objWord.ActivePrinter = "Followprint"
(...)

In VBA, the keyword Set is only used to assign an object to a variable (eg the result of the Documents.Open -function).在 VBA 中,关键字Set仅用于将对象分配给变量(例如Documents.Open函数的结果)。 If you use it when trying to assign anything that is not an object, the compiler (or the runtime) will throw the Object required error message.如果在尝试分配不是对象的任何内容时使用它,编译器(或运行时)将抛出Object required错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM