'Compile Error' - 'Object required' VBA Code

2019-05-13 excel vba ms-word

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

    ' Restore the original printer
    objWord.ActivePrinter = previousPrinter


    objWord.Quit SaveChanges:=False

End Sub


ActivePrinter returns a string with the name of the printer, not an object. Therefore, declare previousPrinter as string and simply assign the result of ActivePrinter to it.

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). 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.