Reputation: 121
Private Function SelectAPrinter(myName As String) As Printer
Dim strComputer As String
Dim objWMIService As Object
Dim myPrinter As Object
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set myPrinter = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")
Set SelectAPrinter = myPrinter
End Function
so of course VB6 barks at me with "type mismatch" which is no surprise. I am attempting to set an object (myPrinter) to type Printer.
I DO NOT Know how to finish this function. IS THERE a method of "casting" an object to type Printer?
Upvotes: 0
Views: 198
Reputation: 8868
You can use a helper method to "cast" the object to a Printer. However, the helper method does use the Printers collection:
Private Function SelectAPrinter(myName As String) As Printer
Dim MyWMIService As Object
Dim MyPrinters As Object
Dim MyPrinter As Object
Set MyWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set MyPrinters = MyWMIService.ExecQuery("Select Name from Win32_Printer where Name = '" & myName & "'")
For Each MyPrinter In MyPrinters
Set SelectAPrinter = FindPrinter(MyPrinter.Name)
Exit For
Next
End Function
Private Function FindPrinter(ByVal DeviceName As String) As Printer
Dim p As Printer
For Each p In Printers
If UCase(p.DeviceName) = UCase(DeviceName) Then
Set FindPrinter = p
Exit For
End If
Next
End Function
Upvotes: 1
Reputation:
If you do not mind setting the default printer temporarily, then perhaps the following will work.
Option Explicit
Private Sub Command1_Click()
Dim saveme As String
Dim yourprinter As Printer
saveme = Printer.DeviceName
Set yourprinter = SelectAPrinter("Canon iR-ADV C5045/5051 PCL5c")
Debug.Print "selected", yourprinter.DeviceName ' Microsoft Print to PDF
Call SelectAPrinter(saveme) ' restore default
Debug.Print "restored", Printer.DeviceName
End Sub
Private Function SelectAPrinter(myName As String) As Printer
Dim strComputer As String
Dim objWMIService As Object
Dim colInstalledPrinters As Object
Dim myPrinter As Object
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery("Select * from Win32_Printer where Name = '" & myName & "'")
For Each myPrinter In colInstalledPrinters
myPrinter.SetDefaultPrinter
Exit For
Next
Set SelectAPrinter = Printer
End Function
Upvotes: 1