I'm needing to set my printer to "Microsoft Print to PDF" but how would I know which port it will be on? It could be different on another machine. I need to it to be able to set it without knowing the port "on XXXX:" part like this:
Application.activeprinter = "Microsoft Print to PDF"
Any help would be appreciated. Thanks
?ActivePrinter 'show active printer "XXXXXX on XXXX:"
CodePudding user response:
- The simplest way:
Try manually printing (anything) from Excel on the above printer.
Then use the next code line: Debug.Print Application.ActivePrinter. It will return in Immediate Window the printer name string (port included) to be used in case of setting it as Active.
- The next code returns the printer with its port, being called with printer name as argument:
Function FindPrinter(ByVal PrinterName As String) As String
Dim arrH, Pr, Printers, Printer As String
Dim RegObj As Object, RegValue As String
Const HKEY_CURRENT_USER = &H80000001
Set RegObj = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
RegObj.Enumvalues HKEY_CURRENT_USER, "Software\Microsoft\Windows NT\CurrentVersion\Devices", Printers, arrH
For Each Pr In Printers
RegObj.getstringvalue HKEY_CURRENT_USER, "Software\Microsoft\Windows NT\CurrentVersion\Devices", Pr, RegValue
Printer = Pr & " on " & Split(RegValue, ",")(1)
If InStr(1, Printer, PrinterName, vbTextCompare) > 0 Then
FindPrinter = Printer
Exit Function
End If
Next
End Function
It can be called in the next way:
Sub testFindPrinter()
Debug.Print Application.ActivePrinter
Debug.Print FindPrinter("Microsoft Print to PDF")
End Sub
Or, simple set the active printer in the next way:
Application.ActivePrinter = FindPrinter("Microsoft Print to PDF")
