If you've tried to change the printer in Excel VBA, no doubt you've realised that it needs the printer port in order to work, this looks something like "NE01:". As this changes from computer to computer it can't be hard coded.
Here's a solution that will get the printer port without looping over all possible versions until one works.
Public Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias _
"RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, _
ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Public Declare Function RegQueryValueEx Lib "advapi32.dll" Alias _
"RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As _
String, ByVal lpReserved As Long, lpType As Long, lpData As Any, _
dwSize As Long) As Long
Public Declare Function RegCloseKey Lib "advapi32.dll" _
(ByVal hKey As Long) As Long
Private Const dhcKeyAllAccess = &H2003F
Private Const HKEY_CURRENT_USER = &H80000001
Private Const dhcRegSz As String = 1
Function GetPrinterPort(PrinterName As String) As String
Dim hKeyPrinter As Long
Dim lngResult As Long
Dim strBuffer As String
Dim cb As Long
lngResult = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\Windows NT\CurrentVersion\Devices", 0&, dhcKeyAllAccess, hKeyPrinter)
If lngResult = 0 Then
strBuffer = Space(255)
cb = Len(strBuffer)
lngResult = RegQueryValueEx(hKeyPrinter, PrinterName, 0&, dhcRegSz, ByVal strBuffer, cb)
If lngResult = 0 Then GetPrinterPort = Right(Left(strBuffer, cb), 6)
lngResult = RegCloseKey(hKeyPrinter)
End If
End Function
Below is an example for calling it:
strPrinterPort = GetPrinterPort("\\KNV-PRT-P0003\PRT-TOSH-Q-01")
Hope this helps someone
Bookmarks