Search code examples
vb6printersnetwork-printers

How to create a Printer object in VB


I am facing an issue in VB 6 while creating a Printer Object. Basically, I need to create a printer object so that I can set the correct tray on which printing needs to be performed.

I have the Printer Name with me.

All the code that I am able to find online involves looping through all the available printers and finding a match with our printer name.

Is there a way I can create the Printer object prn directly from the Printer name.

Any help would be appreciated.


Solution

  • You can't. The VB6 Printers collection is accessed only by index, not by name. See Visual Studio 6 Printer Object, Printers Collection.

    So you have to search the collection for the printer you want. For instance:

    Private Function FindPrinter(PrinterName As String) As Printer
      Dim i As Integer
      For i = 0 To Printers.Count - 1
        If Printers(i).DeviceName = PrinterName Then
          Set FindPrinter = Printers(i)
          Exit For
        End If
      Next i
      Exit Function
    End Function
    

    The above doesn't handle the situation where the printer you're looking for isn't in the collection. You'll want to add logic to cover that condition - what you'll want to do is specific to your particular tasks and requirements. This example is also a case-sensitive name search, so keep that in mind, too.