Microsoft Excel VBA - WMIを利用してプリンターの一覧を取得する方法

◆概要

このページは、Excel VBAでWMIを利用してプリンターの一覧を取得する方法について記載しています。

 WMIを利用すると、システムの様々な情報を取得することができます。ここでは、接続されているプリンター一覧を取得するコードを掲載します。

Sub GetPrinterName()
    On Error GoTo ErrProc

    Dim strComputer As String
    Dim oWmiService As Object
    Dim oCollection As Object
    Dim oItem       As Object

    'ローカルホストに接続する
    strComputer = "."

    Set oWmiService = GetObject( _
        "winmgmts:{impersonationLevel=impersonate}!\\" & _
      strComputer & "\root\cimv2")

    'プリンタの一覧を取得する
    Set oCollection = oWmiService.ExecQuery _
        ("Select * From Win32_Printer")

    For Each oItem In oCollection
      Debug.Print oItem.Name
    Next

    Set oCollection = Nothing
    Set oWmiService = Nothing

    Exit Sub

ErrProc:
  MsgBox Err.Description, "エラー"
End Sub

このコードを実行すると、イミディエイトウィンドウにプリンターの一覧が表示されます。


▼ページトップへ