WordのCommandBarオブジェクトの一覧を、Wordの表として作成するマクロをご紹介しました。
WordのCommandBarオブジェクト一覧を、Excelに出力するマクロも作ってみました。
WordのCommandBarオブジェクト一覧をExcelに出力するサンプルマクロ
以下のWordマクロを実行すると、WordのCommandBarオブジェクト一覧が新規Excelブックに作成されます。
Dim xl_app As Object, xl_bk As Object
Set xl_app = CreateObject("Excel.Application")
xl_app.Visible = True
Set xl_bk = xl_app.Workbooks.Add
Dim xl_sht As Object
Set xl_sht = xl_bk.Sheets(1)
xl_sht.Cells(1, "A").Value = "Index"
xl_sht.Cells(1, "B").Value = "Name"
xl_sht.Cells(1, "C").Value = "NameLocal"
Dim i As Long
With Word.Application.CommandBars
For i = 1 To .Count
xl_sht.Cells(i + 1, "A").Value = .Item(i).Index
xl_sht.Cells(i + 1, "B").Value = .Item(i).Name
xl_sht.Cells(i + 1, "C").Value = .Item(i).NameLocal
Next
End With
xl_sht.Range("A1:C1").Font.Bold = True
xl_sht.Columns("A:C").AutoFit
サンプルマクロで行っている処理
最初にVBAのCreateObject関数で、Excel.Applicationオブジェクトへの参照を取得して、Excel.Applicationを表示します。
Dim xl_app As Object, xl_bk As Object Set xl_app = CreateObject("Excel.Application") xl_app.Visible = True
次に、一覧を出力するためのExcelブックを、Excel.Application.Workbooks.Addメソッドを使って新規に作成します。
Set xl_bk = xl_app.Workbooks.Add
続いて、作成した新規ブックの先頭のワークシートを変数xl_shtに代入しておきます。
この後のExcelに関わる処理は、このxl_shtを経由して行います。
Dim xl_sht As Object Set xl_sht = xl_bk.Sheets(1)
A1:C1セルに見出しの文字列を入力して、
xl_sht.Cells(1, "A").Value = "Index" xl_sht.Cells(1, "B").Value = "Name" xl_sht.Cells(1, "C").Value = "NameLocal"WordのCommandBarオブジェクトのIndex・Name・NameLocalを出力しています。
Dim i As Long With Word.Application.CommandBars For i = 1 To .Count xl_sht.Cells(i + 1, "A").Value = .Item(i).Index xl_sht.Cells(i + 1, "B").Value = .Item(i).Name xl_sht.Cells(i + 1, "C").Value = .Item(i).NameLocal Next End WithCommandBarオブジェクトの一覧を出力し終わったら、A1:C1セルに太字を設定して、A:C列の列幅を調整しています。
xl_sht.Range("A1:C1").Font.Bold = True xl_sht.Columns("A:C").AutoFit
Home » ワードマクロ・Word VBAの使い方 » Office連携 » WordのCommandBarオブジェクト一覧をExcelに出力するマクロ