2015-08-18 101 views

回答

1

您需要檢查從WMI查詢中檢索到的打印機對象的Port屬性。在下面的示例中,您可以從WMI查詢中刪除WHERE子句以獲取所有已安裝的打印機,然後您可以測試每臺打印機上的端口。很顯然,並非所有打印機都有IP(XPS Document Writer等)。

Sub Main() 

    Debug.Print GetPrinterPort("HP Color LaserJet CP4005 PCL6") 

End Sub 

Function GetPrinterPort(printerName As String) As String 

    Dim oWMI As Object 
    Dim oPrinters As Object 
    Dim oPrinter As Object 
    Dim sPort As String 

    sPort = "" 

    Set oWMI = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2") 

    Set oPrinters = oWMI.ExecQuery("Select * from Win32_Printer WHERE name = '" & printerName & "'") 

    If Not oPrinters Is Nothing Then 
    For Each oPrinter In oPrinters 
     sPort = oPrinter.PortName 
     Exit For 
    Next 
    End If 

    Set oWMI = Nothing 
    Set oPrinters = Nothing 
    Set oPrinter = Nothing 

    GetPrinterPort = sPort 

End Function