VBA Printer and Printers object requires installing Reference library?

108 views Asked by At

I have a question for Printer object and Printers object in Excel VBA. Is any Reference library required to install in the Tool->Reference before we can use Pinter and Printers object?

I run below code, and get error "object is required" for line For Each prt In Printers. The Printers object is empty and prt-object is Nothing.

Sub ListPrinters()
    Dim prt As Printer
    For Each prt In Printers
        Debug.Print Prt.deviceName
    Next prt
End Sub

I tried to add reference library in Tool-> reference menu, and could not find any reference for Printer or Printers.

1

There are 1 answers

0
FunThomas On

Application.Printers does not exist in Excel or Word, it exists only in Access (didn't check for Powerpoint or any other MS Applications).

Alternative is to use the method EnumPrinterConnections of the Windows Scripting Host:

Sub ListPrinters2()
    Dim i As Long
    With CreateObject("WScript.Network")
        For i = 1 To .EnumPrinterConnections.Count Step 2
          Debug.Print .EnumPrinterConnections(i)
        Next
    End With
End Sub

The loop might look a little bit strange with the Step 2. Reason is that every printer has 2 entries in the list, the first gets the port, the second the printer name.